这个问题是节点还没创建渲染完就读取节点,这个时候应该先让节点渲染完成在生成,解决方法有以下两种
1、使用$nextTick()方法进行,这个方法是用来在节点创建渲染完成后进行的操作
that.$nextTick(() => {
let qrcode = new QRCode("qrcode", {
width: 132,
height: 132,
text: "https://www.baidu.com/", // 二维码地址
colorDark: "#000",
colorLight: "#fff",
});
});
2、使用延时方法
setTimeout(function () {
new QRCode("qrcode", {
width: 132,
height: 132,
text: "https://www.baidu.com/", // 二维码地址
colorDark: "#000",
colorLight: "#fff",
});
}, 200);
相比之下还是第一种比较好,延时不能精确
原文“vue项目使用qrcodejs2遇到Cannot read property ‘appendChild‘ of null“_scarecrowll的博客-CSDN博客
vue使用qrcodejs2进行二维码显示以及下载
1、安装qrcodejs2
npm install --save qrcodejs2
2、引入qrcodejs2
import QRCodejs from 'qrcodejs2';
3、使用
html:
<div ref="locatorQRCodeRef"></div>
<!-- 作为下载二维码使用 -->
<a ref="locatorQRCodeDownloadLinkRef" style="display: none"></a>
js:
new QRCodejs(this.$refs.locatorQRCodeRef, {
text: ‘www.baidu.com’, // 需要变成二维码的文本
width: 260,
height: 260,
colorDark: '#333', // 二维码颜色
colorLight: '#fff', // 二维码背景颜色
correctLevel: QRCodejs.CorrectLevel.L //容错率,L/M/H
});
let qrcodeCanvas = ((this.$refs.locatorQRCodeRef || {})?.getElementsByTagName?.('canvas') || [])?.[0];
this.qrcodeImgUrl = qrcodeCanvas?.toDataURL?.('image/png'); // 作为下载图片资源
vue:
<template>
<div>
<div id="qrcode"></div> <!-- 创建一个div,并设置id为qrcode -->
</div>
</template>
<script>
import QRCode from 'qrcodejs2' // 引入qrcode
export default {
name : 'test',
mounted () {
this.qrcode();
},
methods: {
qrcode() {
let qrcode = new QRCode('qrcode', {
width: 132,
height: 132,
text: 'https://www.baidu.com', // 二维码地址
colorDark : "#000",
colorLight : "#fff",
})
},
}
}
</script>
4、效果
5、下载二维码功能(打印功能在另外一篇:https://www.cnblogs.com/zaijin-yang/p/16896229.html)
handleDownloadLocatorQRCode() {
let downloadLink = this.$refs.locatorQRCodeDownloadLinkRef;
downloadLink.setAttribute('href', this.qrcodeImgUrl);
downloadLink.setAttribute(
'download',
`二维码_${new Date().getTime()}.png`
);
downloadLink.click();
URL.revokeObjectURL(downloadLink.href);
},
原文:https://www.cnblogs.com/zaijin-yang/p/16896566.html