1.安裝qrcodehtml
npm install qrcode
2.組件中引入qrcodenpm
import QRCode from 'qrcode'
3.html代碼服務器
<div><span class="right-btn" @click="makeQRCode">生成二維碼</span></div> <div class="column-body-content text-center"> <div class="qr-code"> <img id="image" :src="qrcode"> <p>掃碼預覽</p> </div> </div> <style lang="stylus" scoped> .right-btn position relative display inline-block margin-right: 20px padding: 2px 6px line-height: 20px font-size 12px color: #fff border-radius: 4px background-color #29e cursor pointer .column-body-content padding: 20px .qr-code position relative margin-right: 20px margin-bottom: 10px display inline-block img width: 120px height: 120px border: 1px solid #eee p line-height 20px font-size 12px text-align center </style>
4.使用qrcode:調用QRCode.toDataURL(二維碼掃描的url)方法,可生成所須要的二維碼dom
// 生成二維碼 makeQRCode() { QRCode.toDataURL("http://aaa.vv.com/erp/card?authkey="+this.companyId).then(imgData => { if(imgData) { let file = this.convertBase64UrlToBlob(imgData); // 上傳到服務器(這裏是上傳到阿里雲,this.oss是直接把阿里雲的oss鏈接做爲Vue對象的屬性來調用,put是上傳文件的方法) this.oss.put('qrcode' + Math.random()*10 + '.png', file).then(result => {
this.qrcode = result.url; // 將已上傳的圖片的url賦值給img的src alert('生成成功') }) } }); }, //從 base64 轉換成 file convertBase64UrlToBlob(urlData) { let bytes = window.atob(urlData.split(',')[1]); //去掉url的頭,並轉換爲byte //處理異常,將ascii碼小於0的轉換爲大於0 let ab = new ArrayBuffer(bytes.length); let ia = new Uint8Array(ab); for (let i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab] , {type : 'image/png'}); }