项目需求,点击表格中下载二维码按钮弹出二维码,再点击下载,将二维码保存在本地
此时需要用到html2canvas这个插件
npm i html2canvas --save //现在安装插件
引入:
import html2canvas from "html2canvas"; //引入html2canvas
使用:
html2canvas(document.getElementById("2canvas")).then((canvas) => {
var pageData = canvas.toDataURL("image/png", 1.0); //第二个参数可以调节下载图片的清晰度
const link = document.createElement("a");//创建一个a标签
link.style.display = "none"; //去掉此标签的所有样式避免展示出a标签
link.href = pageData; //把获取到的流文件放到href属性里
link.setAttribute("download", this.organize_task_name + ".png");//调用download属性,并添加名字
document.body.appendChild(link);//添加这个a标签到body上
link.click(); //触发click事件
});
完整代码:
<!-- 导出的二维码 -->
<el-dialog title="下载二维码" :visible.sync="showDownload" width="480px">
<div class="qr_code" id="2canvas">
<h1 class="header_title">{{ organize_task_name }}</h1>
<img class="img_qrCode" :src="el_img_url" alt="" />
<span>有效期至:{{ end_date }}</span>
<span>所属社区:{{ organize_name }}</span>
</div>
<div slot="footer">
<el-button @click="showDownload = false">取 消</el-button>
<el-button type="primary" @click="handleDownloadqrCode"
>确 定</el-button
>
</div>
</el-dialog>
js:
//下载二维码
handleDownload(row) {
if (row.qrCode === null) {
this.msgError("此数据暂无二维码");
return;
}
this.end_date = row.endDate;
this.organize_name = row.organizeName;
this.organize_task_name = row.organizeTaskName;
this.el_img_url = row.qrCode;
this.showDownload = true;
},
// 根据dom生成图片并下载到本地
handleDownloadqrCode() {
html2canvas(document.getElementById("2canvas")).then((canvas) => {
var pageData = canvas.toDataURL("image/png", 1.0); //第二个参数可以调节下载图片的清晰度
const link = document.createElement("a");
link.style.display = "none";
link.href = pageData;
link.setAttribute("download", this.organize_task_name + ".png");
document.body.appendChild(link);
link.click();
});
},