qrcodejs2-npm: https://www.npmjs.com/package/qrcodejs2

1. 安装

npm i qrcodejs2

2. 组件中引入并封装成公共组件

<template>
  <div style="width: 100%;height: 100%;" :id="id" :ref="id"></div>
</template>
<script>
import QRCode from 'qrcodejs2'
export default {
  data() {
    return {
      qrcode: ''
    }
  },
  props: {
    id: {
      type: String,
      required: true
    },
    text: {  // 后端返回的二维码地址
      type: String,
      default: 'http://jindo.dev.naver.com/collie'
    },
    width: {
      type: String,
      default: '128'
    },
    height: {
      type: String,
      default: '128'
    },
    colorDark: {
      type: String,
      default: '#000000'
    },
    colorLight: {
      type: String,
      default: '#ffffff'
    }
  },
  watch: {
    text(newText) {
      this.createQrcode()
    }
  },
  mounted() {
    this.createQrcode()
  },
  methods: {
    createQrcode() {
      if(this.qrcode) {  // 有新的二维码地址了,先把之前的清除掉
        this.$refs[this.id].innerHTML = ''
      }
      this.qrcode = new QRCode(this.$refs[this.id], {
        text: this.text, //页面地址 ,如果页面需要参数传递请注意哈希模式#
        width: this.width, // 二维码宽度 (不支持100%)
        height: this.height, // 二维码高度 (不支持100%)
        colorDark: this.colorDark,
        colorLight: this.colorLight,
        correctLevel: QRCode.CorrectLevel.H,
      })
    },
    // 制作另一个二维码
    updateCode() {
      this.qrcode.makeCode("http://naver.com")
    }
  }
}
</script>

3. 组件中使用

<template>
  <div style="width: 100%;height: 100%;">
    <QrCode :id="'QrCode'" :text="codeUrl" />
  </div>
</template>
<script>
import QrCode from './qrCode.vue'  // 引用上面封装的二维码组件
export default {
  data() {
    return {
      codeUrl: 'http://jindo.dev.naver.com/collie'  // 后端返回的二维码地址
    }
  },
  components: { QrCode },
  mounted(){
    setTimeout(() => { // 模拟有新的二维码地址
      this.codeUrl = 'http://naver.com'
    }, 2000)
  },
}
</script>

4. 效果 

 

清除二维码 

一般我们拿到后台数据后,生成二维之前会初始化一下,也就是把之前的绘制的二维码 清除掉

 两种方式 

this.$refs.qrcode.innerHTML = ''; //清除二维码方法一
this.qrcode.clear();  // 清除二维码方法二

 制作另一个二维码

qrcode.makeCode("http://naver.com"); // make another code.
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐