1.在项目使用node安装qrcodejs2
2.在需要使用二维码打印的页面中引入
3.页面代码
<template>
<div>
<el-button @click="printCode">打印二维码</el-button>
</div>
</template>
<script>
export default {
methods:{
printCode() {
this.printClick()
},
printClick() {
const _self = this
let printContent = ''
const pLength = _self.allStudent.length // pLength为所要打印的数组对象的长度
for (let i = 0; i < pLength; i++) {
// 这里是构建的内容=》可以在新页面中写好,再用模板字符串链接起来
printContent += ` <div style='display:flex;justify-content:center;align-items:center;flex-direction:column; width: 50%;height:50%;float:left'>
<div style='display:flex;justify-content:center;align-items:center;flex-direction:column;width:100mm;'>
<div style='display:flex;justify-content: space-between;align-items:center;width: 100%;'>
<div>
<h1>${_self.allStudent[i].studentName}</h1>
<p style='font-size: 16px;'>${_self.getGender(_self.allStudent[i].gender.id)} ${
_self.allStudent[i].age
}岁</p>
<p style='font-size: 16px;'>${_self.className}</p>
</div>
<div id='XQ${i}'></div>
</div>
<div style='width:100%'>
<table border="1" style='width:100%;border-collapse:collapse'>
<thead>
<tr style='width:100%;height:50px;font-size: 12px;'>
<th>XXXX</th>
<th>XXXX</th>
</tr>
<tbody>
<tr style='width:100%;height:50px'>
<td></td>
<td></td>
</tr>
<tr >
</tbody>
</thead>
</table>
</div>
</div>
</div>`
}
// const printAfter = '</tr></tbody></table>'
_self.printHtml = printContent
document.getElementById('qrcode2').innerHTML = _self.printHtml
const new_str = document.getElementById('qrcode2').innerHTML // 获取指定打印区域
// 构建新网页(关键步骤,必须先构建新网页,在生成二维码,否则不能显示二维码)
document.body.innerHTML = new_str
document.body.style.width = 297 + 'mm'
for (let j = 0; j < _self.allStudent.length; j++) {
document.getElementById('XQ' + j).innerHTML = '' // 置空
const contentStr = _self.allStudent[j].studentId // 二维码内容
// 生成二维码
var qrcode = new QRCode(document.getElementById('XQ' + j), {
// 二维码内容
text: contentStr,
// 大小
width: 100,
height: 100,
colorDark: '#000000',
colorLight: '#ffffff'
})
}
setTimeout(function() {
window.print() // 打印刚才新建的网页
window.location.reload()
})
return false
},
}
}
</script>
<style>
</style>
效果如下