·需求:后端给二维码内容链接,前端把链接转为二维码,二维码超时可点击按钮刷新二维码
·html
<template>
<div class="wechat">
<div ref="qrCode" v-loading="loading" class="qrCode"></div>
<p>请使用微信扫描二维码支付,请在5分钟内完成支付,过期请刷新支付码</p>
<el-button @click="refresh">刷新二维码</el-button>
</div>
</template>
·JS
<script>
import QRCode from "qrcodejs2";
export default {
data() {
return {
qrCode: null,
};
},
props: ["wxPayCode", "loading"],//wxPayCode是外层组件传入链接内容;loading是加载二维码的动画
methods: {
refresh() {
//调用外层组件请求二维码链接内容的函数,重新请求二维码链接
this.$emit("getWxPayCode", "wx");
},
crateQrcode() {
if (this.qrCode) {
// 二维码过期,需要清空二维码容器,再次请求
//一定要清空容器!!!
this.$refs.qrCode.innerHTML = "";
this.qrCode = new QRCode(this.$refs.qrCode, {
width: 106,
height: 103, // 高度
text: this.wxPayCode, // 二维码内容
// render: 'canvas' // 设置渲染方式(有两种方式 table和canvas,默认是canvas)
// background: '#f0f',
// foreground: '#ff0'
});
// console.log(qr)
} else {
this.qrCode = new QRCode(this.$refs.qrCode, {
width: 106,
height: 103, // 高度
text: this.wxPayCode, // 二维码内容
// render: 'canvas' // 设置渲染方式(有两种方式 table和canvas,默认是canvas)
// background: '#f0f',
// foreground: '#ff0'
});
// console.log(qr);
}
},
},
watch: {
wxPayCode(newValue, oldValue) {
if (newValue) {
this.$nextTick(() => {
this.crateQrcode();
});
}
},
},
};
</script>
·css
<style lang="scss">
.wechat {
width: 100%;
height: 250px;
display: flex;
align-items: flex-end;
flex-wrap: wrap;
justify-content: center;
.qrCode {
width: 106px;
height: 103px;
display: inline-block;
background-color: #ccc;
}
p {
font-size: 12px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: rgba(153, 153, 153, 1);
line-height: 17px;
margin-top: 14px;
width: 100%;
text-align: center;
}
.el-button {
width: 100px;
height: 36px;
font-size: 14px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #3071fe;
line-height: 20px;
padding: 0;
border: 1px solid #3071fe;
background: #deecff;
border-radius: 0;
}
}
</style>
·第一次使用时遇到的坑
①页面元素必须使用ref=“string”,用于获取需要渲染二维码的元素
②如果有点击刷新二维码的需求,刷新二维码之前一定要清空包裹二维码容器的内容(npm插件库中qrcodejs2(0.0.2版本)可以使用qrCode.clear()方法清除之前的二维码,我使用时报错,找不到clear方法)
③第一次做这种功能,不足之处,留言指出