调用手机扫描二维码功能

912 阅读1分钟

在vue移动端开发时,很多时候需要调用手机底层的一些功能来实现业务,所以在使用Hbuilder打包的前提下调用Hbuilder的二维码plus模块,来实现 二维码扫描功能,二维码的状态和使用最好在vuex中赋值,以方便控制。

在mounted阶段调用下面代码片段

startRecognize(){
   let that = this
    if (!window.plus) return
    // 使用vuex来创建scan二维码
    that.$store.commit('changescan', new plus.barcode.Barcode('qrcode'))
    // 设置扫描之后的函数回调
    that.$store.commit('changeonmarked',onmarked)
    // 开始扫描
    that.$store.commit('staticScan')
    //设置扫描二维码页面样式,根据需求自行调整
    barcode.setStyle({
        background:'#8f9494',
        height:"100%"
    });
    //成功之后的函数回调
    function onmarked(type, result, file) {
        switch (type) {
        case plus.barcode.QR:
            type = 'QR'
            break
        case plus.barcode.EAN13:
            type = 'EAN13'
            break
        case plus.barcode.EAN8:
            type = 'EAN8'
            break
        default:
            type = '其它' + type
            break
        }
        // 获得扫描的二维码路径
        result = result.replace(/\n/g, '')
        //在data中设置变量codeUrl
        that.codeUrl = result
    }
}

在退出二维码页面时需要将二维码扫描关闭,不然会一直在页面中显示

	this.$store.commit('closeScan')

下面是vuex 中的的调用

const state = {
    scan:null
  }
const mutations = {
  //创建
  changescan(state, data) {
    state.scan = data
  },
  //成功回调
  changeonmarked(state, data){
      state.scan.onmarked = data
  },
  //开始扫描
  staticScan(state){
      state.scan.start();
  },
  //关闭二维码
  closeScan(state){
      state.scan.close();
  }
}
export default {
  state,
  mutations
}
  

另外在Android移动端需要控制物理返回键退出二维码页面,在APP.vue 的mounted阶段调用此函数

bindBack() {
   let vm = this;
   let first = null;
   plus.key.addEventListener("backbutton", () => {
       if (
         this.$route.name == "LabManagerIndex" ||
         this.$route.name == "LogingIndex"||
         this.$route.name == "gaugerIndex"||
         this.$route.name == "EquipmentengineerIndex"
       ) {
       //此处是需要直接退出app的页面路由
         if (!first) {
           first = new Date().getTime(); //记录第一次按下回退键的时间
           plus.nativeUI.toast("再按一次退出应用");
           setTimeout(function() {
             //1s中后清除
             first = null;
           }, 2000);
         } else {
           if (new Date().getTime() - first < 2000) {
             //如果两次按下的时间小于1s,
             plus.runtime.quit(); //那么就退出app
           }
         }
       }else if(this.$route.name == 'QRcodeIndex'){
       //二维码页面
          this.$router.back(-1)
         this.$store.commit('closeScan')
       }else{
          this.$router.back(-1)
       }
   });
 },