vue自动生成二维码并下载打印到本地
作者:互联网
1、安装
npm i vue-qriously -S
2、引入,main.js文件
// 二维码 import VueQriously from 'vue-qriously' Vue.use(VueQriously)
3、使用
<Button type="info" @click="scan">查看</Button>
<Button type="info" @click="download">下载</Button> <!-- 二维码 --> <Modal v-model="isShowQrcode" :closable="false" width="232" :footer-hide="true"> <qriously id="qrcode" :value="qrcode_url" :size="200" />
<p style="textAlign:center;">请使用微信扫一扫</p>
</Modal>
<script> data() { return { isShowQrcode:false,//二维码弹窗 qrcode_url:"",//二维码显示内容 } }, methods:{ // 查看二维码 scan(){ this.isShowQrcode = true;//打开二维码弹窗 this.qrcode_url = "二维码需要显示的内容"; },
// 下载二维码 download() { this.qrcode_url = ""; this.qrcode_url = "维码需要显示的内容"; // 先找到canvas节点下的二维码图片 let myCanvas = document.getElementById("qrcode").getElementsByTagName("canvas"); // 创建一个a节点 let a = document.createElement("a"); // 设置a的href属性将canvas变成png格式 let imgURL = myCanvas[0].toDataURL("image/jpg"); let ua = navigator.userAgent; if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且 windows系统 情况下 才执行; var bstr = atob(imgURL.split(",")[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } var blob = new Blob([u8arr]); window.navigator.msSaveOrOpenBlob(blob, "download" + "." + "png"); } else if (ua.indexOf("Firefox") > -1) { //火狐兼容下载 let blob = this.base64ToBlob(imgURL); //new Blob([content]); let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为 a.download = " "; //下载图片名称,如果填内容识别不到,下载为未知文件,所以我这里就不填为空 a.href = URL.createObjectURL(blob); a.dispatchEvent( new MouseEvent("click", { bubbles: true, cancelable: true, view: window, }) ); //兼容火狐 } else { //谷歌兼容下载 // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream') a.href = myCanvas[0].toDataURL("image/jpg"); //设置下载文件的名字 a.download = "download"; //点击 a.click(); } },
//base64转blob base64ToBlob(code) { let parts = code.split(";base64,"); let contentType = parts[0].split(":")[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); } } </script>
标签:vue,image,打印,二维码,let,blob,download,new 来源: https://www.cnblogs.com/yunjiao/p/16485001.html