Vue-cli4 唤醒摄像头扫描二维码

<template>
  <div class="scan">
    <div id="bcid">
      <div id="head">
        <van-row>
          <van-col span="4">
            <van-icon name="clear" @click="closeScanBtn" size="2em" />
          </van-col>
          <van-col span="8"></van-col>
          <van-col span="8"></van-col>
        </van-row>
      </div>
      <div style="height:40%"></div>
      <p class="tip">...载入中...</p>
    </div>
  </div>
</template>

<script type='text/ecmascript-6'>
let scan = null;
import Vue from "vue";
import { Col, Row } from "vant";
import { Icon } from "vant";

Vue.use(Icon);
Vue.use(Col);
Vue.use(Row);
export default {
  data() {
    return {
      codeUrl: ""
    };
  },
  destroyed() {},
  mounted() {
    this.startRecognize();
    this.startScan();
  },
  methods: {
    //创建扫描控件
    startRecognize() {
      let that = this;
      if (!window.plus) return;
      scan = new window.plus.barcode.Barcode("bcid");
      scan.onmarked = onmarked;

      // eslint-disable-next-line no-unused-vars
      function onmarked(type, result, file) {
        switch (type) {
          case window.plus.barcode.QR:
            type = "QR";
            break;
          case window.plus.barcode.EAN13:
            type = "EAN13";
            break;
          case window.plus.barcode.EAN8:
            type = "EAN8";
            break;
          default:
            type = "其它" + type;
            break;
        }
        result = result.replace(/\n/g, "");
        that.codeUrl = result;
        that.closeScan();
      }
    },

    //开始扫描
    startScan() {
      if (!window.plus) return;
      scan.start();
    },
    //关闭扫描
    cancelScan() {
      if (!window.plus) return;
      scan.cancel();
    },
    //关闭条码识别控件
    closeScan() {
      if (!window.plus) return;
      scan.close();
      this.$store.state.GetdeviceSn = 0;
      var reg = /^[A-Z][0-9]{12,15}$/;
      if (!reg.test(this.codeUrl)) {
        alert("无效的机器编号");
       this.$router.push({ path: "/NewD/" + this.$store.state.deviceSn });
      } else {
        this.$router.push({ path: "/NewD/" + this.codeUrl });
      }
    },
    closeScanBtn() {
      if (!window.plus) return;
      scan.close();
       this.$store.state.GetdeviceSn = 0;
       this.$router.push({ path: "/NewD/" + this.$store.state.deviceSn });
    }
  }
};
</script>
<style lang="less">
.scan {
  height: 100%;
  background-color: #ccc;
  #bcid {
    width: 100%;
    height: 45rem;

    left: 0;
    right: 0;
    top: 0rem;
    bottom: 0rem;
    text-align: center;
    color: #fff;
    z-index: -1;
    background: #ccc;
  }
  #head {
    position: absolute;
    left: 0rem;
    height: 2rem;
    top: 2rem;
    line-height: 0rem;
    z-index: 1;
    width: 100%;
  }
}
</style>

效果如下

posted @ 2020-04-23 13:50  可乐_加冰  阅读(2185)  评论(3编辑  收藏  举报