vue使用qrcodejs2生成二维码

目录

概要

构建展示的vue组件qrcode.vue

组件的使用


概要

项目中用到需要展示二维码的样式,想到了qrcode

例如:

前提:安装包

npm install qrcodejs2 --save

构建展示的vue组件qrcode.vue

<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: 'M000001'
    },
    width: {
      type: String,
      default: '100'
    },
    height: {
      type: String,
      default: '100'
    },
    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>

组件的使用

<template>

    <div>
    
    /**

    *item为二维码的内容
    *colorDark为前景色

    */
        <QrCode :id="'QrCode'" :text="item" colorDark="#802126"/>
    </div>

</template>
<script>
import QrCode from '../../components/QRcode/qrCode.vue'  // 引用上面封装的二维码组件
export default {
components: { QrCode },//注册组件

}

</script>

小结

这个组件还是相当好用的,多多推荐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值