首先安装二维码模块
cnpm
install
qrcodejs2 --save
页面用
<
div
id
=
"qrCode"
ref
=
"myQrCode"
></
div
>
或者直接
<
div
id
=
"qrCode"
></
div
>
设置具体参数有三种方式:
1.mounted中直接设置:
mounted() {
new
QRCode(
this.$refs.myQrCode, {
text:
"https://www.baidu.com"
,
width: 150,// 宽度
height: 150,
colorDark:
"#333333"
,
//二维码颜色
colorLight:
"#ffffff"
,
//二维码背景色
correctLevel: QRCode.CorrectLevel.L
//容错率,L/M/H
});
}
2.created里用
this.$nextTick的回掉函数
created() {
this
.$nextTick(
function
() {
new
QRCode(
this.$refs.myQrCode, {
text:
"https://www.baidu.com"
,
width: 150,
height: 150,
colorDark:
"#333333"
,
//二维码颜色
colorLight:
"#ffffff"
,
//二维码背景色
correctLevel: QRCode.CorrectLevel.L
//容错率,L/M/H
});
});
}
3.方法里设置,比如点击个按钮弹出来之类的
mounted:
function
() {
this
.$nextTick(
function
() {
this
.bindQRCode();
})
},
methods: {
clickQRCode
() {
new
QRCode(
this.$refs.myQrCode, {
text:
'https://www.baidu.com'
,
width: 150,
height: 150,
colorDark:
"#333333"
,
//二维码颜色
colorLight:
"#ffffff"
,
//二维码背景色
correctLevel: QRCode.CorrectLevel.L
//容错率,L/M/H
})
}
}
生成二维码js必须在 this.$nextTick(function(){调用})或setTimeout(() => { 调用 }, 100),是为了确保二维码容器DOM已经存在
为了防止重复生成二维码document.getElementById("qrcode").innerHTML = "";在方法中置空