// 点击下载 downLoadCode() {const image = new Image();image.setAttribute("crossOrigin", "anonymous");image.onload = () => {const canvas = document.createElement("canvas");canvas.width = image.width;canvas.height = image.height;const context = canvas.getContext("2d");context.drawImage(image, 0, 0, image.width, image.height);const url = canvas.toDataURL("image/png"); // 得到图片的base64编码数据const a = document.createElement("a"); // 生成一个a元素const event = new MouseEvent("click"); // 创建一个单击事件a.download = `${this.rowData.deviceName}二维码`; // 设置图片名称(todo 根据你实际项目修改)a.href = url; // 将生成的URL设置为a.href属性a.dispatchEvent(event); // 触发a的单击事件};image.src = this.codeUrl;}
完整代码
<template><el-dialog:destroy-on-close="true":close-on-click-modal="false":title="title":visible.sync="dialogVisible"width="600px"@close="dialogVisible = false"><divstyle="display: flex;flex-direction: column;justify-content: center;align-items: center;"><img :src="codeUrl" class="codeImg" alt="" /><div class="download" @click="downLoadCode"><i class="iconfont if-xiazai" /><span>点击下载二维码</span></div></div></el-dialog>
</template><script>
import { getQrCode } from "@/api/infoManage/deviceManage/deviceManage";
export default {data() {return {codeUrl: "",dialogVisible: false,title: "",rowData: {}};},methods: {showDialog(data) {this.dialogVisible = true;this.title = data.title;this.rowData = data.data;this.handleCode(data.data);},handleClose() {this.dialogVisible = false;this.codeUrl = "";},/*** 生成二维码* */handleCode(content) {let data = {content: content.id};getQrCode(data).then(res => {const blob = new Blob([res.data], { type: "image/png" });this.codeUrl = window.URL.createObjectURL(blob);}).catch(err => {console.log(err);});},/*** 下载二维码* */downLoadCode() {const image = new Image();image.setAttribute("crossOrigin", "anonymous");image.onload = () => {const canvas = document.createElement("canvas");canvas.width = image.width;canvas.height = image.height;const context = canvas.getContext("2d");context.drawImage(image, 0, 0, image.width, image.height);const url = canvas.toDataURL("image/png"); // 得到图片的base64编码数据const a = document.createElement("a"); // 生成一个a元素const event = new MouseEvent("click"); // 创建一个单击事件a.download = `${this.rowData.deviceName}二维码`; // 设置图片名称a.href = url; // 将生成的URL设置为a.href属性a.dispatchEvent(event); // 触发a的单击事件};image.src = this.codeUrl;}}
};
</script><style lang="scss" scoped>
.download {font-size: 14px;font-family: MicrosoftYaHei;color: #1492ff;margin-bottom: 48px;cursor: pointer;text-align: center;display: flex;align-items: center;justify-content: center;i {margin-right: 5px;}
}
</style>