1、安装依赖
npm install jszipnpm install file-saver --save
2、使用
<template><el-card class="mb15"><template #header><span>jszip</span></template><!-- 二维码容器 --><div id="qrCodeBox"></div></el-card></template><script setup lang="ts" name="demoView">import { ref, onMounted } from 'vue'import QRCode from 'qrcodejs2-fix';import html2canvas from 'html2canvas';import JSZip from 'jszip'import { saveAs } from 'file-saver';const getQrCode = async () => {// 清空二维码容器内容document.getElementById('qrCodeBox').innerHTML = '';new QRCode(document.getElementById('qrCodeBox'), {//需要编码的文字内容或者URLtext: '生成二维码',width: 200, //二维码宽height: 200, //二维码高colorDark: '#000000',colorLight: '#ffffff',correctLevel: QRCode.CorrectLevel.H});// 如果在dialog里展示二维码图片,则需要注意使用nextTick};const base64img = ref()const screenshot = async () => {html2canvas(document.querySelector('#qrCodeBox')).then(canvas => {base64img.value = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '')// 打压缩包tozip()// 如果打包多张截图,参考代码如下/*printImg(arr) {const base64Array = [];arr.forEach(item => {let el = document.querySelector(`#zip${item.id}`)html2canvas(el).then(canvas => {base64Array.push({name: `${item.id}.png`,data: canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '')});if(base64Array.length == arr.length) {this.downloadZip(base64Array,'二维码')}})})},*/})}const tozip = () => {const zip = new JSZip();zip.file('1.png', base64img.value, { base64: true });zip.generateAsync({ type: 'blob' }).then(content => {saveAs(content, `压缩包.zip`)})}onMounted(async () => {// 生成二维码await getQrCode()// 截图await screenshot()})</script><style lang="scss" scoped>#qrCodeBox {width: 200px;height: 200px;}</style>
3、页面
4、效果