eventChannel的用法的一些经验,既好理解,又简单好用。
发布于 3 年前 作者 gshao 2367 次浏览 来自 分享

eventChannel具体用法不多介绍,看文档:

https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateTo.html

eventChannel对于初学者,是有点弯绕,不好理解的,我们对其用法做了修改:

1、父页打开子页,用globalData传参;

2、子页返回父页,用eventChannel传参;

具体代码如下:

pageFather.js:

原做法:

fatherEC1:function(){
    wx.navigateTo({
      url: './child',
      events: {
        ec: e => console.log(e)
      },
      success: res => {
        res.eventChannel.emit('ec', 'father')
      }
    })
  },

现做法:

  fatherEC2:function(){
    app.globalData.ecData = 'father'
    wx.navigateTo({
      url: './child',
      events: {
        ec: e => console.log(e)
      }
    })
  },

pageChild.js:

原做法:

  childEC2:function(){
    this.ec = this.getOpenerEventChannel()
    this.ec.once && this.ec.once('ec', e => {
      console.log(e) //'father'
    })
  },

现做法:

  childEC1:function(){
    console.log(app.globalData.ecData) //'father'
  },

当然从子页里往父页传参还是保持不变:

  onSubmit: function () {
    this.getOpenerEventChannel().emit('ec', 'child')
    wx.navigateBack()
  },
  onDelete: function () {
    this.getOpenerEventChannel().emit('del', true)
    wx.navigateBack()
  },
  onUpdate: function () {
    this.getOpenerEventChannel().emit('update', {data})
    wx.navigateBack()
  },

这样改一下,是不是简单了,好理解多了?

实际上效果也很好,而且大概率不会发生一种叫“21 events balabala”的告警。

1 回复

学习了!

回到顶部