2021/04/29 插件qrcodejs2将后端链接转换成二维码

  • 背景
    需求内有个扫码功能,后端会把链接从接口返回给我,我把收到的链接转换成二维码显示到页面上

  • 步骤

– step1.安装

npm install qrcodejs2 --save

– step2. 引入

–1.可以在main.js 中全局引用(这种方式我会报错)

–2.在使用的页面上局部应用

import QRCode from "qrcodejs2";

–step3.页面上写代码

<template>
  <div>
    <div>
      <p>签章二维码test</p>
    </div>
    <!-- code box 这里可以自己写样式,也可以写加在下个div上 -->
    <div class="code_box">
      <div id="qrcode" ref="qrcode"></div>
    </div>
  </div>
</template>

<script>
	import QRCode from "qrcodejs2";
	data() {
	    return {
	      qCodeUrl: "",
	    };
	},
	mounted() {
    //method1  
     this.$nextTick(() => {
       this.initCode();
     });

    //method2  报错 el.appendChild is not a function
     this.$nextTick(() => {
       setTimeout(() => {
         this.initCode();
       }, 2000);
     });
  },
  methods:{
  	//⚠️**this.$refs.qrcode**不要写成字符串了,否则会一直报错 can't append of null
	var qrcode = new QRCode(this.$refs.qrcode, {
   	text: this.qCodeUrl, // 需要生成二维码的内容
    width: 147,
    height: 147,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.H,
  });
//也可以写成这种
let myCode = new QRCode("qrcode", {
        width: 150, // 二维码宽度
        height: 150, // 二维码高度
        // text: "sdfsdfsf",
        text: this.imgCode,
      });
}
</script>

==我在main.js中这样引入的
在这里插入图片描述
–在页面上使用就会报错 el.appendChild is not a function

–结合$nextTick和setTimeout一起使用,还是会报错,有解决过这个问题的朋友请留言

=更新

–由于dom未渲染完成,调用生成二维码函数会报错,所以,我的代码是在watch中 监听到数据的改变,再来调用生成二维码函数,最好和setTimeout还有$nextTick连用

watch: {
    imgCode: {
      //深度监听,可监听到对象、数组的变化
      handler(val, oldVal) {
        let that = this;
        if (val) {
          that.$nextTick(function (prams) {
            that.createQR();
          });
        }
      },
    },
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值