微信小程序開發——使用第三方插件生成二維碼


需求場景:

小程序中指定頁面需要根據列表數據生成多張二維碼。

實現方案:

鑒於需要生成多張二維碼,可以將生成二維碼的功能封裝到組件中,直接在頁面列表循環中調用就好了。也可以給組件添加slot,在頁面調用時寫入需要跟二維碼組件綁定在一起進行顯示的內容。

技術難點:

微信小程序並沒有提供官方二維碼生成功能魔抗,所以這個就只能自己去找插件實現了。對於網上的插件,有很大一部分都是根據qrcode.js改進的。

對於插件的選擇並不是很順利,第一次選定了weapp-qrcode這個插件,本來開發測試都好好的,到了同事的華為v10上,就會出現間隔性不顯示的問題(兩個頁面之間切換,有時候會不顯示二維碼),這個問題已經在git上提了Issues,並被作者標記為bug。

后邊又找到另一個插件weapp-qrcode-base64,經反復測試驗證,這個插件可以正常使用,已經將這個功能做了個小程序片段,詳見:小程序二維碼生成組件

組件代碼:

components/qrcode/index.js

// components/myComponent.js
const QR = require('./weapp-qrcode.js')
const rpx2px = wx.getSystemInfoSync().windowWidth / 750
Component({
  options: {
    multipleSlots: true // 在組件定義時的選項中啟用多slot支持
  },
  properties: {
    value: String, //二維碼內容
    width: String, //二維碼寬度(默認長寬相等)
  },
  data: {
    qrcodeURL: ''
  },
  ready: function() {
    var imgData = QR.drawImg(this.data.value, {
      typeNumber: 3,//碼點大小 1-40,數字越大,碼點越小,二維碼會顯得越密集
      errorCorrectLevel: 'H',//糾錯等級 H等級最高(30%) 簡單來說,就是二維碼被覆蓋了多少仍然能被識別出來 詳見qrcode.js
      size: parseInt(rpx2px * this.data.width)
    })
    this.setData({
      qrcodeURL: imgData
    })
  },
  methods: {
    /**
     * 長按保存圖片
     */
    save: function() {
      var self = this
      var aa = wx.getFileSystemManager(),
        filePath = wx.env.USER_DATA_PATH + '/qrcode_' + self.data.value + '.png';
      //寫入臨時文件
      aa.writeFile({
        filePath: filePath,
        data: self.data.qrcodeURL.slice(22),
        encoding: 'base64',
        success: res => {
          //保存臨時文件到手機相冊中去
          wx.saveImageToPhotosAlbum({
            filePath: filePath,
            success: function(res) {
              wx.showToast({
                title: '保存成功',
              })
            },
            fail: function(err) {
              console.log(err)
            }
          })
          console.log(res)
        },
        fail: err => {
          console.log(err)
        }
      })
    }
  }
})

components/qrcode/index.wxml

<view class='qrcode'>
  <image src="{{qrcodeURL}}" bindlongpress='save' style="width:{{width}}rpx; height:{{width}}rpx;margin:0 auto;"> </image>
  <slot name="text"></slot>
</view>

頁面引用:

pages/index/index.js

Page({
  data: {
    textArr: [
      "11111111",
      "00000000",
      "7539514682492"
    ]
  },
  onLoad: function() {

  }
})

pages/index/index.wxml

<view wx:for="{{textArr}}">
  <qrcode class="iblock" value="{{item}}" width="440">
    <view slot="text">
      {{item}}
    </view>
  </qrcode>
</view>

上邊組件可以點擊小程序二維碼生成組件導入到微信開發者工具中進行查看。

 


免責聲明!

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



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