Vue使用QRCode.js生成二维码

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'}); }
相关文章
相关标签/搜索