需求:
本项目基于vue2+antd,在组件外点击按钮弹框,弹框内容见图。点击下载按钮保存二维码
实现步骤:
1、安装qrcode2js 插件
npm install qrcodejs2 --save
2、直接上组件吧:
<template>
<div>
<a-modal :title="title" width="300px" :visible="visible || false" :ok-text="'下载二维码'" :cancel-text="'关闭'" @ok="downloadCode" @cancel="handleCancel">
<a id="downloadQRCODE"><div class="qrcode-container" :ref="id" style="width: 100%;height: 100%;" :id="id"></div></a>
</a-modal>
</div>
</template>
<script>
import QRCode from 'qrcodejs2'
export default {
name: 'QRCode2',
components: {},
props: {
visible: {
type: Boolean,
default: false
},
id: {
type: String,
required: true,
default: 'qrcode'
},
title: {
type: String,
default: '查看二维码'
},
text: { // 后端返回的二维码地址
type: String,
default: ''
},
width: {
type: String,
default: '200'
},
height: {
type: String,
default: '200'
},
colorDark: {
type: String,
default: '#000000'
},
colorLight: {
type: String,
default: '#ffffff'
}
},
data () {
return {
qrcodeImg: ''
}
},
watch: {
text: {
immediate: false,
handler (obj) {
this.createQrcode()
}
}
},
mounted () {
},
methods: {
handleCancel () {
this.$emit('onClose', true)
},
createQrcode () {
let qrcodeDiv = document.getElementById(this.id || 'qrcode')
if (!qrcodeDiv) {
this.$nextTick(() => {
qrcodeDiv = document.getElementById(this.id || 'qrcode')
if (qrcodeDiv) {
this.createQrcodeNext(qrcodeDiv)
}
});
}else{
this.createQrcodeNext(qrcodeDiv)
}
},
createQrcodeNext (qrcodeDiv) {
if (this.qrcodeImg) { // 有新的二维码地址了,先把之前的清除掉
this.$refs[this.id || 'qrcode'].innerHTML = ''
}
this.qrcodeImg = new QRCode(qrcodeDiv, {
text: this.text, //页面地址 ,如果页面需要参数传递请注意哈希模式#
width: this.width, // 二维码宽度 (不支持100%)
height: this.height, // 二维码高度 (不支持100%)
colorDark: this.colorDark,
colorLight: this.colorLight,
correctLevel: QRCode.CorrectLevel.H,
})
},
downloadCode(){
const nodeList = Array.prototype.slice.call(this.qrcodeImg._el.children)
const img = nodeList.find((item) => item.nodeName.toUpperCase() === 'IMG') // 选出图片类型
// 构建画布
let canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
// 构造url
let url = canvas.toDataURL('image/png');
document.getElementById('downloadQRCODE').setAttribute('href', url);
document.getElementById('downloadQRCODE').setAttribute('download', `${this.title}-二维码.png`);
document.getElementById('downloadQRCODE').click();
}
}
}
</script>
<style lang="less" scoped>
.qrcode-container{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
</style>
3、调用:
visiable:控制模态框显示隐藏
id:随便给一个
title:弹框名称
text:二维码的内容,别人扫码扫出来的字符串
其他参数:二维码高宽啥的见上面组件中的props
<QrCode
:visible="true"
:id="'QrCode'"
:title="`弹框名称`"
:text="`二维码内容`"
@onClose="()=>qrVisible=false"/>