-
背景
需求内有个扫码功能,后端会把链接从接口返回给我,我把收到的链接转换成二维码显示到页面上 -
步骤
– 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();
});
}
},
},
},