Vue H5项目,怎么引入uni.webview sdk,调用uni postMessage实现手机蓝牙连接打印功能(uniapp)

这篇具有很好参考价值的文章主要介绍了Vue H5项目,怎么引入uni.webview sdk,调用uni postMessage实现手机蓝牙连接打印功能(uniapp)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

目前公司Vue H5项目,用webview打包成APP,现产品提出这样打包出来的app运行较慢,需要用uniapp方式(即使用HBuilder编辑器来打包H5)来打包,那需要的基座就不是安卓的基座而是uniapp的基座,而H5项目实现手机扫描功能就需要调用uniapp的基座的方法。

需求&流程说明

Vue2 开发的移动端项目(H5项目及ipad端项目),需要连接蓝牙设备打印

需求说明:

1、点击打印按钮时,先判断当前设备是否已连接过蓝牙(即是否存在蓝牙设备ID)

a、若已连接过:直接调用打印配置(即:type:bluetoothPrint)
b、若未连接过:

1、先获取当前设备的所有蓝牙list(即:type:getBluetoothList)

uniappwebview 引入sdk,vue专栏,Vue H5移动端项目,vue.js,uni-app,uni.webview,postMessage,蓝牙打印,移动端,H5移动端
2、选中设备后调用蓝牙连接(即:type:connBluetooth)
3、连接成功后存储已连接的设备ID(即选中的设备)

具体步骤

一、Uniapp Webview 源码

<template>
  <view>
    <web-view :src="src" @message="showMessage"></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      src: 'http://******/', // H5项目地址
      qrCodeWv: null,
      devices: [],
      currDev: null,
      connId: '',
    }
  },
  onReady() {
    // #ifdef APP-PLUS
    let currentWebview = this.$scope.$getAppWebview()
    setTimeout(() => {
      this.wv = currentWebview.children()[0]
      this.qrCodeWv = currentWebview.children()[0]
      this.wv.setStyle({ scalable: true })
    }, 1000)
    // #endif
  },
  methods: {
    showMessage(event) {
      if (event.detail.data && event.detail.data.length > 0) {
        let dataInfo = event.detail.data[0]
        console.log(dataInfo)
        let type = dataInfo.type
        if (type === 'getBluetoothList') {
          this.getBluetoothList()
        }
        if (type === 'connBluetooth') {
          console.log(dataInfo.params)
          let args = dataInfo.params;
          let deviceId = args.deviceId;
          let device = this.devices.find((item) => {
            return item.deviceId == deviceId;
          })
          console.log(device)
          this.connBluetooth(device)
        }
        if (type === 'bluetoothPrint') {
          let args = dataInfo.params;
          let deviceId = args.deviceId;
          let command = args.command;
          let device = this.devices.find((item) => {
            return item.deviceId == deviceId;
          })
          //当设备没有连接时需要重新连接设备
          if (this.connId == '') {
            this.initBluetoothList();
            this.connBluetooth(device);
          }
          let serviceId = this.currDev.services[0].serviceId;
          let characteristicId = this.currDev.services[0].characteristicId;
          this.senBlData(deviceId, serviceId, characteristicId, command);
        }
      }
    },
    // 获取蓝牙设备list
    getBluetoothList() {
      this.initBluetoothList();
      const data = JSON.stringify(this.devices)
      console.log('获取蓝牙设备list', data)
      this.qrCodeWv.evalJS(`appBluetoothListResult('${data}')`)
    },
    initBluetoothList() {
      this.searchBle();
      setTimeout(() => {
        this.stopFindBule();
      }, 10000)
    },
    // 查找蓝牙设备
    searchBle() {
      var self = this
      console.log("initBule")
      uni.openBluetoothAdapter({
        success(res) {
          console.log("打开 蓝牙模块")
          console.log(res)
          self.onDevice()
          uni.getBluetoothAdapterState({
            success: function (res) {
              console.log(res)
              if (res.available) {
                if (res.discovering) {
                  self.stopFindBule()
                }
                //搜索蓝牙
                //开始搜寻附近的蓝牙外围设备
                console.log("开始搜寻附近的蓝牙外围设备")
                uni.startBluetoothDevicesDiscovery({
                  success(res) {
                    console.log(res)
                  }
                })
              } else {
                console.log('本机蓝牙不可用')
              }
            },
          })
        }
      })
    },
    onDevice() {
      console.log("监听寻找到新设备的事件---------------")
      var self = this
      //监听寻找到新设备的事件
      uni.onBluetoothDeviceFound(function (devices) {
        //获取在蓝牙模块生效期间所有已发现的蓝牙设备
        console.log('--------------new-----------------------' + JSON.stringify(devices))
        var re = JSON.parse(JSON.stringify(devices))
        let name = re.devices[0].name
        if (name != "未知设备" && name.length != 0) {
          console.log(name.length)
          let deviceId = re.devices[0].deviceId
          //信号过滤。大于50
          //如果已经存在也不用加入
          if (re.devices[0].RSSI > self.filterRSSI) {
            if (!self.devices.some(v => v.deviceId == deviceId)) {
              self.devices.push({
                name: name,
                deviceId: deviceId,
                services: []
              })
            }
          }
        }
      })
    },
    stopFindBule() {
      console.log("停止搜寻附近的蓝牙外围设备---------------")
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res)
        }
      })
    },
    // 连接蓝牙
    connBluetooth(device) {
      this.onConn(device);
    },
    // 连接蓝牙
    onConn(item) {
      var self = this
      console.log(`连接蓝牙---------------${item.deviceId}`)
      let deviceId = item.deviceId
      uni.createBLEConnection({
        deviceId: deviceId,
        complete(res) {
          let result = false;
          if (res.errMsg == "createBLEConnection:ok") {
            plus.nativeUI.toast(`设备:${item.name} 已连接`, {
              verticalAlign: 'center'
            })
            self.connId = deviceId;
            self.currDev = item,
              setTimeout(function () {
                self.getBLEServices(deviceId)
              }, 2000)
            result = true;
          } else {
            plus.nativeUI.toast(`设备: ${item.name} 连接失败。请重试!`, {
              verticalAlign: 'center',
            })
            //切换异常时释放掉链接
            if (self.connId != '') {
              uni.closeBLEConnection({
                deviceId: self.connId,
                success(res) {
                  console.log(res)
                }
              })
            }
          }
          //连接成功 关闭搜索
          self.stopFindBule()
          //发生是否成功结果
          var data = {};
          data.result = result;
          var data1 = JSON.stringify(data)
          self.wv.evalJS(`appConnBluetoothResult('${data1}')`)
        },
      })

    },
    getBLEServices(_deviceId) {
      var self = this;
      let deviceId = _deviceId
      console.log("获取蓝牙设备所有服务(service)。---------------")
      uni.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: deviceId,
        complete(res) {
          console.log(res)
          let serviceId = ""
          for (var s = 0; s < res.services.length; s++) {
            console.log(res.services[s].uuid)
            let serviceId = res.services[s].uuid
            uni.getBLEDeviceCharacteristics({
              // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
              deviceId: deviceId,
              // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
              serviceId: serviceId,
              success(res) {
                var re = JSON.parse(JSON.stringify(res))

                console.log(`deviceId =[${deviceId}] serviceId = [${serviceId}]`)
                for (var c = 0; c < re.characteristics.length; c++) {
                  if (re.characteristics[c].properties.write == true) {
                    let uuid = re.characteristics[c].uuid
                    console.log(`deviceId =[${deviceId}] serviceId = [${serviceId}] characteristics=[${uuid}]`)
                    for (var index in self.devices) {
                      if (self.devices[index].deviceId == deviceId) {
                        self.devices[index].services.push({
                          serviceId: serviceId,
                          characteristicId: uuid
                        })
                        break
                      }

                    }
                    console.log(JSON.stringify(self.devices))
                  }
                }
              }
            })

          }
        },
        fail(res) {
          console.log(res)
        },
      })

    },
    senBlData(deviceId, serviceId, characteristicId, uint8Array) {
      var uint8Buf = Array.from(uint8Array);

      function split_array(datas, size) {
        var result = {};
        var j = 0
        if (datas.length < size) {
          size = datas.length
        }
        for (var i = 0; i < datas.length; i += size) {
          result[j] = datas.slice(i, i + size)
          j++
        }
        //result[j] = datas
        console.log(result)
        return result
      }
      var sendloop = split_array(uint8Buf, 20);
      // console.log(sendloop.length)
      function realWriteData(sendloop, i) {
        var data = sendloop[i]
        if (typeof (data) == "undefined") {
          return
        }
        //console.log("第【" + i + "】次写数据"+data)
        var buffer = new ArrayBuffer(data.length)
        var dataView = new DataView(buffer)
        for (var j = 0; j < data.length; j++) {
          dataView.setUint8(j, data[j]);
        }
        uni.writeBLECharacteristicValue({
          deviceId,
          serviceId,
          characteristicId,
          value: buffer,
          success(res) {
            console.log('发送成功', i)
            setTimeout(() => {
              realWriteData(sendloop, i + 1);
            }, 100)
          },
          fail(e) {
            console.log('发送数据失败')
            console.log(e)
          }
        })
      }
      var i = 0;
      realWriteData(sendloop, i);
    },
  }
}
</script>

二、H5 Vue项目引入js

1、在public新建js文件夹uni.webview.1.5.4.js文件,其源码地址

https://gitee.com/dcloud/uni-app/raw/dev/dist/uni.webview.1.5.4.js

2、index.html 引入 public/js 下文件

<script src="<%= BASE_URL %>js/uni.webview.1.5.4.js"></script>

3、main.js 定义回调方法和对象

// 蓝牙设备列表
window.appBluetoothListResult = function (val) {
  window.appBluetoothListResultString = val
  window.dispatchEvent(new CustomEvent('bluetoothListResult'))
}

// 蓝牙连接成功或失败
window.appConnBluetoothResult = function (val) {
  window.appConnBluetoothResultString = val
  window.dispatchEvent(new CustomEvent('connBluetoothResult'))
}

4、Vue扫码页面代码

1、在mixins文件夹下新建bluetoothMixins.js:代码如下
export default {
  data() {
    return {
      bluetoothShow: false, // 蓝牙设备弹窗
      deviceId: '', // 蓝牙设备ID
      listArr: [] // 获取所有蓝牙设备
    }
  },
  created() {
    window.addEventListener('bluetoothListResult', this.handleBluetoothList, false)
    window.addEventListener('connBluetoothResult', this.handleConnBluetoothResult, false)
  },
  beforeDestroy() {
    window.removeEventListener('bluetoothListResult', this.handleBluetoothList)
    window.removeEventListener('connBluetoothResult', this.handleConnBluetoothResult)
  },
  methods: {
    handleConnBluetoothResult() {
      const result = window.appConnBluetoothResultString
      console.log('返回蓝牙是否连接成功', result)
      if (JSON.parse(result).result) {
        console.log('连接成功')
        const deviceId = localStorage.getItem('bluetoothDeviceId')
        localStorage.setItem('bluetoothDeviceId', deviceId || this.deviceId)
        // alert(`${this.deviceId}---设置值选中的值`)
        // alert(`${deviceId}---设置值缓存的值`)
        this.bluetoothShow = false
      }
    },
    handleBluetoothList() {
      const result = window.appBluetoothListResultString
      console.log('返回蓝牙list', result)
      if (result) {
        this.bluetoothShow = true
        this.listArr = JSON.parse(result)
      }
    },
    // 选中设备
    selectBluetooth(item) {
      console.log('选中设备', item)
      this.deviceId = item.deviceId
      uni.postMessage({
        data: {
          action: 'connBluetooth',
          params: { deviceId: this.deviceId }
        }
      })
    }
  }
}

2、实际Vue页面:如下
import BluetoothMixins from '@/mixins/bluetoothMixins'
export default {
  mixins: [BluetoothMixins],
  methods: {
  // 点击打印按钮
   async print(deliveryNo) {
      console.log('配送单deliveryNo----', deliveryNo)
      // 获取蓝牙打印参数
      const res = await this.$api.getDeliveryPrintParam({ deliveryNo })
      if (res.success) {
      // 判断之前是否有连接过蓝牙
        const deviceId = localStorage.getItem('bluetoothDeviceId')
        // alert(`${deviceId}---配送单缓存值`)
        if (deviceId) {
          // 连接过直接打印
          uni.postMessage({
            data: {
              action: 'bluetoothPrint',
              params: { deviceId, command: JSON.parse(res.data) }
            }
          })
        } else {
        // 没有连接过,先去获取蓝牙设备数据(list)
          uni.postMessage({
            data: {
              action: 'getBluetoothList'
            }
          })
        }
      }
    }
   }
 }

相关文章

基于ElementUi再次封装基础组件文档


基于ant-design-vue再次封装基础组件文档


vue3+ts基于Element-plus再次封装基础组件文档文章来源地址https://www.toymoban.com/news/detail-831298.html

到了这里,关于Vue H5项目,怎么引入uni.webview sdk,调用uni postMessage实现手机蓝牙连接打印功能(uniapp)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 安卓WebView(H5)调用原生相机及相册

    在开始叙述正文之前笔者先声明一下应用场景:例如在网页上的即时通讯需要能拍照或者从图库选择图片来进行上传,此场景下就可以用到这篇文章的内容 正文 首先,如果你已经把相机以及访问文件夹的权限都加上了并且WebView的基础操作都做完了,就差上传图片了的话那就参

    2024年02月11日
    浏览(30)
  • uni-app 使用webview加载H5打开微信小程序

    最近公司有个需求要求在app里点击一个功能打开小程序,并且关闭小程序回到app,模仿平安保险app。 毕竟我也是刚学习uni-app,找了很多资料,找到了一个天天外链的网站可以生成一个小程序的链接,使用uni的webview去加载这个链接,很好,需求满足,但是收费,那能不能自己

    2023年04月18日
    浏览(46)
  • 使用vue2开发uni-app项目--引入uview-ui

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 目录 前言 一、安装 1、安装uview-ui 2、安装scss支持 二、配置 1、在main.js中引入uView库 2、uni.scss文件中引入uView的全局SCSS主题文件  3、在APP.vue文件中引入uView基础样式 4、在pages.json中 配置easycom组件模式

    2024年02月04日
    浏览(49)
  • 微信小程序和webview使用postMessage交互

    小程序和webview能交互,但是没有你想的那个完美 小程序向webview传递参数只能使用url携带参数 webview向小程序传递参数可以使用postMessage, 但是注意了,postMessage只会在特定的时机执行 ,请看官方文档 由此可见,如果你想点击webview中的一个按钮A,然后给小程序发消息,然后由

    2024年02月02日
    浏览(41)
  • 前后端分离项目,vue+uni-app+php+mysql电影院售票系统(H5移动项目) 开题报告

      毕业论文 基于Vue.js电影院售票系统(H5) 开题报告 学    院:                        专    业:                          年    级:                         学生姓名:                        指导教师:       黄菊华  

    2024年02月07日
    浏览(38)
  • 微信小程序webview(H5页面)调用微信小程序支付

    1.业务描述:微信小程序商城入口进入的页面是商城H5页面,在H5页面进行微信支付如何实现; 2.微信小程序(webview访问H5页面)必须使用微信小程序支付; 如何实现以及实现方式以及支付后页面返回功能: 商品详情(h5页面)--商品确认页(h5页面)--收银台(h5页面)(点击调

    2024年02月11日
    浏览(33)
  • js封装SDK 在VUE、小程序、公众号直接调用js调用后端接口(本文以vue项目为例)

    1.封装一个js文件 msgSdk.js 注意:需要修改这个请求地址  apiServiceAddress 2.在index.html中引入 msgSdk.js文件 和 jquery文件 3.在页面中调用

    2024年04月27日
    浏览(27)
  • uniapp+vue3+vite+ts搭建项目引入uni-ui和uviewPlus组件库

    一、创建项目架构 首先使用官方提供的脚手架创建一个项目 在这里插入代码片 ,这里我创建的 vue3 + vite + ts 的项目: (如命令行创建失败,请直接访问 gitee下载模板) 二、下载依赖 启动 三、下载安装包 引入uni-ui src/package.json 文件配置easycom模式 引入uview-plus main.ts配置 u

    2024年02月13日
    浏览(40)
  • uni-app(Vue3/Vite) + vant UI(Vue3版本)+ js 按需引入的项目搭建

            因为要完成软件工程的项目,要做一个nativeApp,看了很多的技术文档以后决定使用多端兼容的uni-app来开发。组件方面的话最后决定使用目前比较火的Vant UI。但是看了CSDN和掘金上面的很多文章,似乎没有一篇是关于uni-app中使用Vite对vant组件进行按需引入(可能这个

    2023年04月09日
    浏览(45)
  • 已解决:安卓自带的webview加载前端h5项目白屏时长严重,vue首页加载白屏时间过长,那我让app进入的时候就提前加载网页

    自己写的vue项目,自己写的安卓壳子,本来自己觉得慢,忍忍就过去了,但是人家觉得慢,你不得改么?结果是前端自己开发,安卓也自己开发,想甩个锅都没法甩,总不能甩给后端吧?哈哈哈 描述一下我的情况,我写了一个vue项目,需要嵌在安卓里运行,没想到安卓webvi

    2024年02月03日
    浏览(48)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包