需求,web端生成二维码,将二维码和名字下载成图片
使用插件:
- qrcode: 用来生成二维码
- html2canvas:用来创建画布,将二维码和其描述生成canvas画布
安装插件:npm i qrcode html2canvas
将生成二维码封装为组件
src\components\qrcode.vue
<template>
<div class="qr" :id="uuid">
<img class="qr__img" :src="qrBase64" @load="imgLoad" />
<slot />
</div>
</template>
<script>
import QRcode from 'qrcode'
import html2canvas from 'html2canvas'
export default {
props: {
qrContent: {
type: String,
default: ''
}
},
data () {
return {
uuid: `qr_${this._uid}_code`, // 组件唯一ID
qrBase64: ''
}
},
watch: {
qrContent: {
handler: function () {
this.qrContent && this.init()
},
immediate: true
}
},
methods: {
async init () {
this.qrBase64 = await this.createQR(this.qrContent)
},
createQR (content, options) {
return new Promise((resolve, reject) => {
QRcode.toDataURL(content, options).then(url => {
resolve(url)
})
})
},
createCanvas () {
return new Promise((resolve, reject) => {
const container = document.querySelector(`#${this.uuid}`)
html2canvas(container).then(canvans => {
const base64 = canvans.toDataURL('image/png')
resolve(base64)
})
})
},
// 需要等图片加载完才能生成canvas
async imgLoad () {
const canvansBase64 = await this.createCanvas()
this.$emit('input', canvansBase64) // 把目标base64丢出去
}
}
}
</script>
<style scoped>
.qr{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.qr__img{
width: 100%;
height: 200px;
}
</style>
调用
parent.vue
<template>
<div class="body-box padding10">
<div class="page-left back-color">
<el-button type="primary" @click="getCode" size="small">预览二维码</el-button>
</div>
<el-dialog class="my-dialog"
title="二维码"
:visible.sync="codeVisible"
width="500px"
>
<div class="content">
<div style="height: 260px;width: 200px;margin: auto;">
<qrcode :qrContent="qrcode.content" v-model="qrcode.url">
<div class="text">
<span class="black">{{ qrcode.codeTitle }}</span>
</div>
</qrcode>
</div>
<div style="height: 60px;line-height: 60px; text-align: center;margin-top: 10px;">
<el-button @click="savePic">下载</el-button>
</div>
</div>
</el-dialog>
</div>
</template>
<script>
import qrcode from '@/components/qrcode.vue';
export default {
components:{
qrcode,
},
data() {
return {
codeVisible:false,
qrcode:{
content:'',
codeTitle:'',
url:''
},
};
},
created() {
},
methods: {
getCode(row) {
this.codeVisible = true;
this.qrcode = {
content: '1ac1540d5fc14eeea94c87950d456f44',
codeTitle: '巡检点1',
url:''
}
},
//保存图片
savePic() {
console.log('url地址:',this.qrcode.url)
const link = document.createElement("a");//创建一个a标签
link.style.display = "none"; //去掉此标签的所有样式避免展示出a标签
link.href = this.qrcode.url; //把获取到的流文件放到href属性里
link.setAttribute("download", this.qrcode.codeTitle + ".png");//调用download属性,并添加名字
document.body.appendChild(link);//添加这个a标签到body上
link.click(); //触发click事件
},
</script>
<style scoped lang="less">
/* 样式 */
</style>