vue中使用qrcodejs2生成二维码并实现下载

首先保证项目中已经安装qrcodejs2依赖,如果没安装可执行

npm install qrcodejs2 --save-dev

安装完成后直接复制下面的代码封装为一个组件即可

<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
      },
      //扫描二维码跳转的地址
      codeUrl: {
        type: String,
        default: ''
      },
      width: {
        type: String,
        default: '200'
      },
      height: {
        type: String,
        default: '200'
      },
      colorDark: {
        type: String,
        default: '#000000'
      },
      colorLight: {
        type: String,
        default: '#ffffff'
      },
      //下载的二维码名称
      codeName: {
        type: String,
        default: 'code'
      }
    },
    watch: {
      codeUrl(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.codeUrl,
          width: this.width,
          height: this.height,
          colorDark: this.colorDark,
          colorLight: this.colorLight,
          correctLevel: QRCode.CorrectLevel.H,
        })
      },
      //下载
      download(){
        let canvasData = this.$refs[this.id].getElementsByTagName('canvas')
        let a = document.createElement("a");
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.href = canvasData[0].toDataURL("image/png");
        a.download = this.codeName;
        a.dispatchEvent(event);
      }
    }
  }
</script>

如何引用组件?在想用到的页面直接import引用即可

<div class="m-qrcode">
      <div>版本:1.5.0</div>
      <div>更新时间:2024-05-17</div>
      <QrCode ref="qrCode" :code-name="'分享'" :id="'QrCode'" :codeUrl="codeUrl" width="100" height="100" class="qrcode-pic"></QrCode>
    </div>

如何下载?在页面添加下载按钮,直接按照下面的方式写即可

<a-button type="primary" @click="downloadQrCode">下载</a-button>

downloadQrCode(){
         this.$refs.qrCode.download()
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值