小程序生成二维码(使用weapp-qrcode)以及相应的bug汇总

效果展示

小程序生成二维码(使用weapp-qrcode)以及相应的bug汇总_第1张图片

github 地址

github 地址 https://github.com/MrITzhongzi/small_routine_components/tree/master/6.create_qr_code

下载weapp-qrcode

可以通过小程序的npm功能下载:

npm i weapp-qrcode -S

小程序引入

  1. 方法一

    		import drawQrcode from 'weapp-qrcode';
    
  2. 方法二 把npm下载的程序包中dist文件夹中的文件引入(任意引入一个都可以)

小程序生成二维码(使用weapp-qrcode)以及相应的bug汇总_第2张图片

需要把这个js文件复制到自己的项目,然后

import xxx from 'xxxxx';

使用方法

  • 核心代码展示
  // 页面被展示
      console.log(typeof drawQrcode)
      const ctx = wx.createCanvasContext('myQrcode', this);
      let that = this;
      // 在组件实例进入页面节点树时执行
      drawQrcode({
     
        width: 200,
        height: 200,
        ctx: ctx,
        text: that.data.showData,
        callback(){
     
         
        }
      })

小程序 组件封装好

  • createQrCode.json
{
     
  "component": true,
  "usingComponents": {
     }
}
  • createQrCode.wxml
<view class="qrcode-box" style="width: 200px; height: 200px;margin: 0 auto;">
  <canvas style="width: 200px; height: 200px;background: white;" canvas-id="myQrcode">canvas>
view>
  • createQrCode.js
import drawQrcode from 'weapp-qrcode';
Component({
     
  /**
   * 组件的属性列表
   */
  properties: {
     
    showData: {
     
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
     

  },

  lifetimes: {
     
    attached: function() {
     
      // 页面被展示
      console.log(typeof drawQrcode)
      const ctx = wx.createCanvasContext('myQrcode', this);
      let that = this;
      // 在组件实例进入页面节点树时执行
      drawQrcode({
     
        width: 200,
        height: 200,
        ctx: ctx,
        text: that.data.showData,
        callback(){
     
         
        }
      })
    },

    detached: function() {
     
      // 在组件实例被从页面节点树移除时执行
    },
  },
  pageLifetimes:{
     
    show: function() {
     
       
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
     

  }
})

使用封装好的组件

  • 第一步 配置
{
     
  "usingComponents": {
     
    "qr_code": "/component/create_qr_code/createQrCode"
  },
  "navigationBarTitleText": "升级公告"
}
  • 第二部使用

<qr_code showData="hahha">qr_code>

其中showData是我们传入要展示的内容。

注意事项

	const ctx = wx.createCanvasContext('myQrcode', this);

在组件中,小程序生成canvas对象时,如果不穿入 this,小程序就会去页面的上下文中寻找canvas对象,这样就会导致canvas找不到,二维码显示不出来。所以一定传入this,让程序在组件内部寻找canvas对象。

~~~~被这个问题坑哭了,警示后来者……

你可能感兴趣的:(前端学习笔记,canvas,二维码,weapp)