微信小程序跨页面通信

简单业务场景,比如用户中心进入修改手机号页面,修改成功后用户中心需要立马调用setData来修改显示数据,最优的方法是使用发布/订阅模式

创建Event类,event.js

class Event {

  on (event, fn, ctx) {
      if (typeof fn != "function") {
          console.error('fn must be a function')
          return
      }
      
      this._stores = this._stores || {}
      
      ;(this._stores[event] = this._stores[event] || []).push({cb: fn, ctx: ctx})
  }

  emit (event) {
      this._stores = this._stores || {}
      var store = this._stores[event], args

      if (store) {
          store = store.slice(0)
          args = [].slice.call(arguments, 1)
          for (var i = 0, len = store.length; i < len; i++) {
              store[i].cb.apply(store[i].ctx, args)
          }
      }
  }

  off (event, fn) {
      this._stores = this._stores || {}

      // all
      if (!arguments.length) {
          this._stores = {}
          return
      }

      // specific event
      var store = this._stores[event]
      if (!store) return

      // remove all handlers
      if (arguments.length === 1) {
          delete this._stores[event]
          return 
      }

      // remove specific handler
      var cb
      for (var i = 0, len = store.length; i < len; i++) {
          cb = store[i].cb
          if (cb === fn) {
              store.splice(i, 1)
              break
          }
      }
      return
  }   
}

module.exports = Event

app.js引入event.js,确保每个page都能调用

const Event = require('./utils/event.js')
App({
  event: new Event(),
  ...

发布消息页面 (修改手机号页面)

let app = getApp();

Page({
  formSubmit: function(e) {
    //发布修改手机号事件
    app.event.emit('eventUpdateMobile', mobile);
  }
})

订阅消息页面 (个人中心)

let app = getApp();
Page({
  onLoad: function (options) {
    //订阅消息
    app.event.on('eventUpdateMobile', this.eventUpdateMobile, this)
  },

  eventUpdateMobile(mobile) {
    this.setData({"mobile": mobile})
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //必须注销掉之前订阅的事件
    app.event.off('eventUpdateMobile')
  },
})

 

参考: https://aotu.io/notes/2017/01/19/wxapp-event/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值