1.首先下载插件

npm install qrcodejs2 --save

2. 引入

import QRCode from 'qrcodejs2'

3.代码实现如下:

<span class="QRCode_show" @click="handDownInage()">下载二维码</span>
<script>
import QrCode from "qrcode";
export default{
data() {
    return {
      txid:'',
      qrcode: null,
      pushUnitName:'',
      uplinkTime:''
    }
  },
 mounted() {
    console.log('传过来的数据',this.row)
    this.txid = this.row.txid
    this.pushUnitName= this.row.pushUnitName
    this.uplinkTime= this.row.uplinkTime
  },
 methods: {
//下载按钮
    handDownInage() {
      console.log("txid", this.txid);
      let txid = this.txid;
      if ((txid)) {
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          let image = QrCode.toDataURL(txid);
          image.then((res) => {
            console.log("下载", res);
            this.downloadImg(res);
          });
        });
      }
},
//下载图片
    downloadImg(value) {
       console.log("下载图片1", this.pushUnitName, this.uplinkTime);
       let pushUnitName = this.pushUnitName;
       let uplinkTime = this.uplinkTime;
      //实例化一个img对象
      const img = new Image();
      //设置img的图片路径
      img.src = value;
      //设置跨域解决
      img.setAttribute("crossOrigin", "Anonymous");
      //img加载完后处理
      img.onload = function () {             
        //创建一个canvas对象
        const canvas = document.createElement("canvas");
        //把图片的宽度设为canves的宽度
        canvas.width = 230;
        //把图片的高度设为canves的高度
        canvas.height = 230;
        //创建一个2d画布
        const ctx = canvas.getContext("2d");
        // 将img中的内容画到画布上
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        // 将画布内容转换为Blob
        canvas.toBlob((blob) => {
          console.log("blob", blob);
          // blob转为同源url
          let blobUrl = window.URL.createObjectURL(blob);
          // 创建a链接
          const a = document.createElement("a");
          a.href = blobUrl;
          a.download = pushUnitName + uplinkTime;
          // 触发a链接点击事件,浏览器开始下载文件
          a.click();
        });
      };
    },
}
}
</script>

Logo

前往低代码交流专区

更多推荐