vue2在线生成二维码

亲情提示:如果可以让后端生成就让后端生成 实在不行再前端解决(分享方法只是为了让你快点下班  不是为了让你能者多劳)

创建

npm install qrcodejs2  
pnpm install qrcodejs2 

<div ref="qrcode" id="myQrCode" class="qrImg" style="display: flex;align-items: center;justify-content: center;"></div>

import QRCode from 'qrcodejs2'

data:{
  qrcode: '',
}

submitCode() {
  <!-- 每次生成前先清除二维码 -->
  if (this.$refs.qrcode) {
    this.qrcode = '';
    this.$refs.qrcode.innerHTML = ''; // 清除二维码方法
  }
  try {
        getPayMerchantQrCode({
          merchantId: this.zfbId,
          channelId: 1,
          totalAmount: this.zfbForm.price,
          subject: this.zfbForm.subject,
        }).then((res) => {
          this.$message.success("生成成功");
          this.zfbOpen = false
          this.skmOpen = true
          this.$nextTick(() => {
            // 这里生成最新的二维码照片渲染
            this.qrcode = new QRCode(this.$refs.qrcode, {
              width: 300,  // 二维码宽度 (不支持100%)
              height: 300, // 二维码高度(不支持100%)
              text: res.data.qrCode, // 后端返回的二维码地址,这里暂时写死
              render: 'canvas', // 设置渲染方式(有两种方式 table和canvas,默认是canvas)
            });
          })
        });
      } catch (error) {
        console.log(error)
      }
}

下载

downLoadQrcode() {
    let img = document.getElementById("myQrCode").getElementsByTagName['img'][0] // 获取二维码图片标签
    let canvas = document.createElement('canvas') // 创建画布
    canvas.width = img.width
    canvas.height = img.height
    let ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0)
    let tempUrl = canvas.toDataURL('image/png') // 画布生成base64格式图片
    // 创建a标签,模拟点击下载
    let a = document.createElement('a')
    a.setAttribute('download','我的二维码.png')
    a.style.display = 'none'
    a.href = tempUrl
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

家里有只小肥猫

你的鼓励支持我更好的分享经验

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

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

打赏作者

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

抵扣说明:

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

余额充值