小程序海报分享实践与填坑

280 阅读1分钟

开发小记录

从小程序二维码长按或扫描进入小程序需要对scene参数做解析,但是因为小程序中 Page级别的生命周期只有onLoad能获取到options参数,onShow不行,而App级别的生命周期 onLoad onShow中都可以获取到参数。

第一步在Appjs中获取参数 (mpvue中代码如下)

onLoad (options) {
    if (options.query.scene) {
      const query = decodeURIComponent(options.query.scene)
      const goodsSn = query.split('=')[1]

      Vue.prototype.globalData = {
        goodsSn,
        scene: options.scene
      }
    }
  },
  onShow (options) {
    if (options.query.scene) {
      const query = decodeURIComponent(options.query.scene)
      const goodsSn = query.split('=')[1]

      Vue.prototype.globalData = {
        goodsSn,
        scene: options.scene
      }
    }
  }
}

将数据挂载到vue原型的做法见仁见智,可根据需求换成vuex或loaclstorage

第二步,在页面中生命周期获取数据

 onLoad () {
    let goodsSn
    if (this.qrScene.includes(this.globalData && this.globalData.scene)) {
      goodsSn = this.globalData && this.globalData.goodsSn
    } else {
      goodsSn = this.$route.query.goodsSn
    }
    // xxx业务逻辑
  },
  onShow () {
    let goodsSn
    if (this.qrScene.includes(this.globalData && this.globalData.scene)) {
      goodsSn = this.globalData && this.globalData.goodsSn
    } else {
      goodsSn = this.$route.query.goodsSn
    }
    // xxx业务逻辑
  },
  • 在onload 和 onshow 两个钩子中都做了逻辑最主要的原因在于,小程序中独特的 生命周期触发,用户第一次扫码进入时会触发全局onload,在小程序还存在于后台活动时,第二次扫码进入会触发onshow。

待完善