首先保证项目中已经安装qrcodejs2依赖,如果没安装可执行
npm install qrcodejs2 --save-dev
安装完成后直接复制下面的代码封装为一个组件即可
<template>
<div style="width: 100%;height: 100%;" :id="id" :ref="id"></div>
</template>
<script>
import QRCode from 'qrcodejs2'
export default {
data() {
return {
qrcode: ''
}
},
props: {
id: {
type: String,
required: true
},
//扫描二维码跳转的地址
codeUrl: {
type: String,
default: ''
},
width: {
type: String,
default: '200'
},
height: {
type: String,
default: '200'
},
colorDark: {
type: String,
default: '#000000'
},
colorLight: {
type: String,
default: '#ffffff'
},
//下载的二维码名称
codeName: {
type: String,
default: 'code'
}
},
watch: {
codeUrl(newText) {
this.createQrcode()
}
},
mounted() {
this.createQrcode()
},
methods: {
// 有新的二维码地址了,先把之前的清除掉
createQrcode() {
if (this.qrcode) {
this.$refs[this.id].innerHTML = ''
}
this.qrcode = new QRCode(this.$refs[this.id], {
text: this.codeUrl,
width: this.width,
height: this.height,
colorDark: this.colorDark,
colorLight: this.colorLight,
correctLevel: QRCode.CorrectLevel.H,
})
},
//下载
download(){
let canvasData = this.$refs[this.id].getElementsByTagName('canvas')
let a = document.createElement("a");
let event = new MouseEvent("click"); // 创建一个单击事件
a.href = canvasData[0].toDataURL("image/png");
a.download = this.codeName;
a.dispatchEvent(event);
}
}
}
</script>
如何引用组件?在想用到的页面直接import引用即可
<div class="m-qrcode">
<div>版本:1.5.0</div>
<div>更新时间:2024-05-17</div>
<QrCode ref="qrCode" :code-name="'分享'" :id="'QrCode'" :codeUrl="codeUrl" width="100" height="100" class="qrcode-pic"></QrCode>
</div>
如何下载?在页面添加下载按钮,直接按照下面的方式写即可
<a-button type="primary" @click="downloadQrCode">下载</a-button>
downloadQrCode(){
this.$refs.qrCode.download()
},