参考Vue批量生成二维码并打包下载
首先我们需要安装三个插件
"jszip"//zip打包
"file-saver"//文件保存
"vue-qr"//二维码
完整代码如下:
src/components/QRcode/index.vue
<template>
<div>
<div v-for="(item, index) in qrCodeData" :key="index">
<vue-qr
:id_name="'qcode_' + index"
:text="item.url"
:callback="getQcodeUrl"
:bindElement="false"
:qid="item.qid"
></vue-qr>
</div>
</div>
</template>
<script>
import JSZip from "jszip";
import FileSaver from "file-saver";
import vueQr from "vue-qr";
export default {
props: ["qrCodeData","zipName"],
components: {
vueQr,
JSZip,
FileSaver,
},
data() {
return {
qrCodeFile: [],
};
},
methods: {
getQcodeUrl(url, name) {
var that = this;
this.qrCodeFile.push({
url: url,
name: name,
});
if (this.qrCodeFile.length == this.qrCodeData.length) {
const zip = new JSZip();
this.qrCodeFile.forEach((item) => {
const fileName = item.name + ".png";
zip.file(fileName, item.url.substring(22), { base64: true }); //向zip中添加文件
});
zip.generateAsync({ type: "blob" }).then((content) => {
// 生成二进制流
FileSaver.saveAs(content, that.zipName + "--二维码.zip"); // 利用file-saver保存文件
});
this.$emit("closeDownload");
this.qrCodeFile = [];
}
},
},
};
</script>
二维码还有一些属性没有添加,比如logo图片,大小之类的,如果需要可以根据vue-qr,文档自行添加
页面中使用
views/table/index.vue
<template>
<div class="demo">
<el-card class="box">
<el-row style="margin-top: 20px">
<el-button
:disabled="multipleSelection.length == 0"
type="primary"
@click="downloadQcode"
>导出二维码</el-button
>
</el-row>
<el-table
:data="tableData"
border
ref="multipleTable"
class="demo_table"
style="width: 100%"
stripe
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="55"> </el-table-column>
<el-table-column
prop="id"
label="编号"
min-width="180"
></el-table-column>
<el-table-column
prop="name"
label="姓名"
min-width="180"
></el-table-column>
<el-table-column
prop="address"
label="地址"
min-width="180"
></el-table-column>
</el-table>
</el-card>
<QrCode
:qrCodeData="multipleSelection"
@closeDownload="closeDownload"
zipName="打包"
v-if="downloadLoading"
/>
</div>
</template>
<script>
import QrCode from "@/components/QRcode/index";
export default {
name: "demo",
components: {
QrCode,
},
data() {
return {
tableData: [],
downloadLoading: false,
multipleSelection: [],
};
},
created() {
//demo数据生成
for (let i = 0; i < 100; i++) {
this.tableData.push({
id:i,
name:`姓名${i}`,
address:`地址${i}`,
})
}
},
methods: {
closeDownload() {
this.downloadLoading = false;
},
downloadQcode() {
this.downloadLoading = true;
},
handleSelectionChange(val) {
val.forEach((e, i) => {
val[i].qid = `${e.name}`;//二维码图片名称标识
val[i].url = `https://www.baidu.com/s?wd=${e.address}`;//二维码文本内容
});
this.multipleSelection = val;
},
},
};
</script>
<style lang="scss" scoped>
.box {
margin: 20px 10px;
padding-top: 20px;
}
.content_top {
margin: 20px 0;
}
.demo_table {
margin-top: 30px;
}
</style>
效果