在移动端H5页面开发或者web端开发中,常常会遇到生成二维码的业务需求,qrcodejs2
是用于制作二维码的javascript库,支持 DOM 中带有 HTML5 Canvas 和表标签的跨浏览器。可以满足业务需求,使用方法如下:
1、插件安装、导入
cnpm install qrcodejs2 --save
// 或者
npm install qrcodejs2 --save
在相应的页面中使用commonjs或者es6模块方式导入qrcodejs2
import QRCode from 'qrcodejs2';
// 或者
let QRCode = require('qrcodejs2');
2、创建容器、实例化
页面增加一个容器标签
<div id="qrcode" ref="qrcode"></div>
creatQrCode() {
let text = '二维码内容'; // 二维码链接内容
let qrcode = new QRCode(this.$refs.qrcode, {
text: text, //二维码内容字符串
width: 128, //图像宽度
height: 128, //图像高度
colorDark: '#000000', //二维码前景色
colorLight: '#ffffff', //二维码背景色
correctLevel: QRCode.CorrectLevel.H, //容错级别
})
}
实例化方法:
qrcode.clear(); // clear the code.
qrcode.makeCode("http://naver.com"); // make another code.
3、案例
<template>
<div ref="qrcode" id="qrcode" class="qrcode"></div>
</template>
<script>
import QRCode from 'qrcodejs2'
export default {
data() {
return {
qrcode: {
},
time_Interval: '', // 定时器
time_Interval_time: 60000 // 定时器时间
}
},
mounted() {
// 定时刷新二维码
const that = this
if (!this.time_Interval) {
that.init()
}
this.time_Interval = window.setInterval(function () {
that.init()
}, that.time_Interval_time)
},
// 离开页面前清除定时器
beforeRouteLeave(to, from, next) {
window.clearInterval(this.time_Interval)
next()
},
beforeDestroy() {
window.clearInterval(this.time_Interval)
},
methods: {
// 二维码生成
init() {
const that = this
const width = window.innerWidth / 100 * 40 // 此行代码表示二维码的宽度为屏幕宽度的40%,width 不支持百分比、不同设备的像素不一样所以此处这样写
// 此处可以根据业务进行异步处理,动态获取二维码参数,刷新二维码
let qrCodeContent = getQrCodeContent() // 伪代码
// 先清除二维码再重新生成
if (this.qrcode.clear) {
// this.qrcode.clear()
this.$refs.qrcode.innerHTML = ''
}
this.qrcode = new QRCode(this.$refs.qrcode, {
text: qrCodeContent , //二维码内容字符串
width: width, //图像宽度
height: width, //图像高度
colorDark: '#000000', //二维码前景色
colorLight: '#ffffff', //二维码背景色
correctLevel: QRCode.CorrectLevel.H, //容错级别
})
}
}
}
</script>
<style scoped>
.qrcode {
width: 40vw;
height: 40vw;
border: 1px solid #ddd;
margin: 12.8vw 0;
}
/* {略} */
</style>
效果:
4、问题处理
4.1 清除已经生成的二维码
方案一: this.$refs.qrcode.innerHTML = '';
方案二: qrcode.clear();
4.2 动态替换二维码的内容
let string='新的内容'
qrcode.makeCode(string)
4.3 报错提醒 Error: code length overflow ?
这是因为url太长,导致二维码加载报错,可以调低容错率来处理。
修改参数:correctLevel: QRCode.CorrectLevel.H ,容错级别,由低到高分别为L M Q H
4.4 字符串较长,二维码显示模糊怎么办?
可以尝试先将生成的二维码倍数扩大,然后在css上面固定显示宽高,这样可以扩大显示像素精度
.qrcode-wrap{
width: 128px;
height: 128px;
}
.qrcode-wrap canvas,
.qrcode-wrap img {
width:100%;
height:100%;
}
<div id="qrcode" ref="qrcode" class="qrcode-wrap"></div>
creatQrCode() {
let text = '二维码内容';
let qrcode = new QRCode(this.$refs.qrcode, {
text: text,
width: 128 * 3, //宽扩大3倍
height: 128 * 3, //高扩大3倍
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H,
})
}
最后:
此插件兼容性性能都挺好的适合在web端、H5 生成二维码