最近项目中有个裂变分享的需求,需要在页面中根据分享人的身份动态生成二维码图片放置在页面中,所以研究了一下这个功能的实现,同时把实现过程记录如下:1.引入二维码生成模块
1.引入二维码生成模块1.引入二维码生成模块
npm install qrcodejs2 --save

npm install qrcodejs2 --save
注意:此处安装qrcodejs2,安装依赖后可在main方法中进行全局引用设置,也可单独某个页面中进行引用设置。2.引入使用
2.引入使用2.引入使用
import QRCode from 'qrcodejs2';
import QRCode from 'qrcodejs2';备注:在main中设置全局可使用 Vue.prototype.qrCode3.页面展示与配置
3.页面展示与配置3.页面展示与配置3.1 html代码
放置生成二维码图片的容器




3.2 js代码
js代码有三种放入位置
第一种:放置在mounted生命周期函数中
mounted() {
new QRCode(this.$refs.qrCodeDiv, {
text: "https://www.baidu.com",
width: 200,
height: 200,
colorDark: "#333333", //二维码颜色
colorLight: "#ffffff", //二维码背景色
correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
});
}

mounted() {
new QRCode(this.$refs.qrCodeDiv, {
text: "https://www.baidu.com",
width: 200,
height: 200,
colorDark: "#333333", //二维码颜色
colorLight: "#ffffff", //二维码背景色
correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
});
}
第二种:放置在created生命周期函数中,但是注意一定要放在this.$nextTick的回掉函数中
created() {
this.$nextTick(function() {
new QRCode(this.$refs.qrCodeDiv, {

text: "https://www.baidu.com",

width: 200,

height: 200,

colorDark: "#333333", //二维码颜色

colorLight: "#ffffff", //二维码背景色

correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
});
});
},

created() {
this.$nextTick(function() {
new QRCode(this.$refs.qrCodeDiv, {

text: "https://www.baidu.com",

width: 200,

height: 200,

colorDark: "#333333", //二维码颜色

colorLight: "#ffffff", //二维码背景色

correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
});
});
},
第三种方式:放置在methods属性中的指定方法中,并且在mouted生命周期函数中调用这个方法(最好也把这个方法的调用放置在this.$nextTick的回掉函数中)
mounted: function () {
this.$nextTick(function () {
this.bindQRCode();
})
},
methods: {
bindQRCode: function () {
new QRCode(this.$refs.qrCodeDiv, {

text: 'https://www.baidu.com',

width: 200,

height: 200,

colorDark: "#333333", //二维码颜色

colorLight: "#ffffff", //二维码背景色

correctLevel: QRCode.CorrectLevel.L//容错率,L/M/H
})
}
}

mounted: function () {
this.$nextTick(function () {
this.bindQRCode();
})
},
methods: {
bindQRCode: function () {
new QRCode(this.$refs.qrCodeDiv, {

text: 'https://www.baidu.com',

width: 200,

height: 200,

colorDark: "#333333", //二维码颜色

colorLight: "#ffffff", //二维码背景色

correctLevel: QRCode.CorrectLevel.L//容错率,L/M/H
})
}
}
4.注意点
4.注意点4.注意点1.显示内容(text所指向内容)必须是UTF-8编码格式。2.生成二维码js必须在 this.$nextTick(function(){调用})或setTimeout(() => { 调用 }, 100),是为了确保二维码容器DOM已经存在。3.为了防止重复生成二维码,使用置空进行控制:document.getElementById("qrcode").innerHTML = "";document.getElementById("qrcode").innerHTML = "";