[Vue generates a QR code] 1. Generate a QR code from the QR code string returned by the backend; 2. Download function

Vue uses the qrcode plugin

1. Only show the effect of one picture

1. Effect diagram:

![Insert picture description here](https://img-blog.csdnimg.cn/5a54d8a38c6a43959864c5c59847c99d.png

Second, the specific code:

1. Installation

npm i qrcodejs2 --save

2. Use on the page

2.1.html

<div id="qrcode" class="erweima" ref="qrcode"></div>

2.2.js

<script type="text/javascript">
	//vue使用qrcode插件将后端返回的二维码字符串生成二维码
	import QRCode from 'qrcodejs2'
	export default {
    
    
		data() {
    
    
			return {
    
    
				qrcode : '',
				qr: '',
			}
		},
		mounted() {
    
    
			this.MyCode()
		},
		methods: {
    
    
			// 我的数据码
			MyCode() {
    
    
				this.$api.POSTTwo(this.$url.MyCode + localStorage.getItem('token'), '', (res) => {
    
    
					this.password = res.Data;
					// this.qrcode = res.Data;
					//具体代码
					this.qr = new QRCode('qrcode', {
    
    
						text: 'userCode=' + this.password,
						width: 160,
						height: 160,
						colorDark: "#000000",
						colorLight: "#ffffff",
						correctLevel : QRCode.CorrectLevel.H
					})
				})
			},
		}
	}
</script>

2. The two-dimensional code displayed in the list cycle (there is a two-dimensional code under each piece of data)

1. Rendering

insert image description here

2. Specific code

①Installation:

npm i qrcodejs2 --save

② Page introduction

//vue使用qrcode插件将后端返回的二维码字符串生成二维码
import QRCode from 'qrcodejs2'

③Display in template

<el-form-item label="二维码:" v-if="dialogStatus == 'seeDetail'">
	<div id="qrcode" class="qrcode" ref="qrCodeUrl"></div>
	<!--下载功能-->
	<el-button style="margin-top: 20px;" size="mini"
	    @click="downloadQRCode(temp.LabelName,temp.EndTime)">二维码下载</el-button>
	    
</el-form-item>

④ js code:

// 点击用户详情时
seeDetail(row) {
    
    
	this.dialogStatus = 'seeDetail'
	console.log('打印row下的二维码字符串', row.LabelCode)

	//防止生成多个。(每次生成之前,把上一次的DOM节点的二维码删除掉,然后再添加新生成的二维码)
	this.$nextTick(function() {
    
    
		let dom = document.getElementById("qrcode");
		while (dom.firstChild) {
    
    
			dom.removeChild(dom.firstChild);
		}
		//调用字符串生成二维码的方法
		this.creatQrCode(row.LabelCode)
	});
},

//字符串生成二维码的方法
creatQrCode(LabelCode) {
    
    
	console.log('获取到的code', LabelCode)
	var qrcode = new QRCode(this.$refs.qrCodeUrl, {
    
    
		text: LabelCode, // 需要转换为二维码的内容
		width: 100,
		height: 100,
		colorDark: '#000000',
		colorLight: '#ffffff',
		correctLevel: QRCode.CorrectLevel.H
	})
},

//下载二维码图片
downloadQRCode(LabelName, EndTime) {
    
    
	let myCanvas = document.getElementById("qrcode").getElementsByTagName("canvas");
	let a = document.createElement("a");
	a.href = myCanvas[0].toDataURL("image/png");
	a.download = LabelName+'--'+EndTime; //图片名(自动匹配标签名称+标签截止时间)
	a.click();
	// console.log('打印下载', LabelName, EndTime)
},


insert image description here

ending~

Guess you like

Origin blog.csdn.net/weixin_48596030/article/details/127861499