在vue项目中,实现将链接生成二维码;可识别跳转,将生成的二维码可转换成图片,并可保存至本地。具体操作步骤如下:
1.安装及引用
首先,实现这个功能需要使用QRCode和html2canvas,所以在使用之前需要安装
npm install --save html2canvas
npm install qrcodejs2 --save
在页面中引入
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
2. html部分
<template>
<div class="code-box" ref="codeBox">
<div ref="qrcode" class="code-content"></div>
</div>
</template>
3. js部分
3.1 二维码生成
watch: {
url(val) {
console.log("val", val)
this.initCode()
}
},
mounted() {
this.initCode()
},
methods: {
initCode() {
// 使用$nextTick确保数据渲染
this.$nextTick(() => {
if (this.url) {
this.codeWidth = Number(this.$refs.codeBox.clientHeight)
this.codeHeight = Number(this.$refs.codeBox.clientWidth)
this.showCode(this.codeWidth, this.codeHeight)
}
})
},
showCode(width, height) {
if (this.$refs.qrcode) {
this.$refs.qrcode.innerHTML = ''
}
const qrcode = new QRCode(this.$refs.qrcode, {
text: this.url, //要跳转的链接
width: width || 200,
height: height || 200,
colorDark: this.colorDark,
colorLight: this.colorLight,
correctLevel: QRCode.CorrectLevel.L // L M H
})
this.createPicture()
},
3.2 生成图片
createPicture() {
html2canvas(this.$refs.qrcode, {
backgroundColor: null,
width: 200,
height: 200
}).then(canvas => {
const imgData = canvas.toDataURL('image/jpeg')
this.imgData = imgData
})
}
这样就可以啦 效果图就先不放了,有帮助的话记得点赞