安装qrcode包
1.npm install qrcodejs2 --save
2. 在你需要用到二维码的页面引入 import QRCode from ‘qrcodejs2’
二维码代码
我的操作逻辑是将二维码放在一个dialog里,点击打开二维码的按钮,弹出对话框 显示二维码,以下是代码:
<el-button type="primary" icon="el-icon-s-grid" @click="show_qrcode(scope.row.name)" :disabled="scope.row.staticQrcodeAuth == 'disable'"></el-button>
<!--这里的disable是项目要求,如果开了显示二维码开关就显示,否则就不显示,可以用v-show 或 v-if实现,看项目具体要求。@click里的scope.row.name是为了下面 拼接 二维码的url用的-->

<!--dialog存放二维码-->
<el-dialog
width="30%"
:before-close="handleClose"
:show-close="false"
:center="true"
title="静态二维码"
@close="closeCode"
:visible.sync="centerDialogVisible"
append-to-body>
<div class="paycode">
<!-- 放置二维码的容器,需要给一个ref -->
<div id="qrcode" ref="qrcode" style="margin:auto;"></div>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="closeCode">关 闭</el-button>
<el-button type="primary" @click="saveImg">下 载</el-button>
</span>
</el-dialog>
显示如图:

// 对话框显示
show_qrcode (val) {
this.centerDialogVisible = true
// 二维码内容,一般是由后台返回的跳转链接
this.qrcode = '我是一个二维码'
// 使用$nextTick确保数据渲染
this.$nextTick(() => {
this.crateQrcode()
})
},
// 生成二维码
crateQrcode () {
let qr = new QRCode('qrcode', {
width: 150,
height: 150, // 高度
text: this.qrcode // 二维码内容
// render: 'canvas' // 设置渲染方式(有两种方式 table和canvas,默认是canvas)
})
console.log(qr)
},
// 关闭弹框,清除已经生成的二维码
closeCode () {
this.$refs.qrcode.innerHTML = ''
this.centerDialogVisible = false
},
//阻止用户点击空白处关闭对话框
handleClose() {
return false
}
二维码下载
saveImg() {
var canvasData = document.getElementById('qrcode').getElementsByTagName('img')//生成二维码之后其实是个img 所以获取完id之后还要获取到这个img 才能下载成功
var a = document.createElement("a");
a.href = canvasData[0].src;
a.download = "二维码.png";
a.click();
}
本文介绍了在Vue项目中使用qrcodejs2生成二维码的步骤,包括安装库、引入模块以及实现二维码的显示和下载功能。在对话框中点击按钮,可以弹出带有二维码的对话框,用户可以进行下载。

1064

被折叠的 条评论
为什么被折叠?



