Vue使用QRCode.js生成二維碼


1.安裝qrcode

npm install qrcode

2.組件中引入qrcode

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)方法,可生成所需要的二維碼

// 生成二維碼
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'}); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM