uniapp EventChannel 页面跳转参数事件传递navigateBack,navigateTo 成功后通知事件区别

问题:navigateBack()emit事件在onload()监听不到

 从A页面跳转到B页面,在B点击产生数据后,跳转回到A,并告诉A点击的数据是什么,使用:

navigateBack()。

(页面跳转流程: A->B ->A)

B页面:

  toPage() {
      uni.navigateBack({
        complete: (res) => {
          console.log(">>>com ", res)
          this.getOpenerEventChannel().emit('selecteCust', this.selectCustomer)
        },
        success: (res) => {
          console.log(">>>res", res)
          // res.eventChannel.emit('testCust', {data: this.selectCustomer})
          // 打开成功的话, 向打开的页面传递数据,传递的事件名:selecteCust
          this.getOpenerEventChannel().emit('selecteCust', this.selectCustomer)

        }
      })
    },

A页面:

eventChannel.on无法监听到B传递过的事件: selecteCust

  onLoad() {
    // 监听事件
    this.ec = this.getOpenerEventChannel();
    console.log(">|--,,,,,,,,,,,eventchannel", this.ec)
    this.ec.on('testCust', (res) => {
      console.log("................selecteCust,监听到了", res)
    })
  },

官方文档

uni.navigateTo()

 

 uni.navigateBack()

 

分析:当前传递参数方式是下级给上级传递消息,使用navigiateBack()话,要在跳转之后再 

解决:

方式1:navigateBack()改成navigateTo()可以

 onLoad() {
   
    // 监听事件
    this.ec = this.getOpenerEventChannel();
    console.log(">|--,,,,,,,,,,,eventchannel", this.ec)
    this.ec.on('testCust', (res) => {
      console.log("................selecteCust,监听到了", res)
      this.customer = res.data
    })
  },

效果:

方式2: 

 A->B->A, A跳转地方添加监听event

 selectA() {
      uni.navigateTo({
        url: '/pages/custList',
        //   页面跳转回来事件监听
          events: {
            selecteCust: (data) => {
              console.log(">>选中的客户是", data)
          }
      })
    },

区分:uni.$on和eventChannel.on使用推荐

 

两者使用起来其实差不多,都可以达到父传子,子传父的作用。但是因为作用域的原因,evenetChannel在不同页面的变量可以重名,eventChannel更适合父传子,uni.$on适合子传父

官方文档:

uni.navigateTo(OBJECT) | uni-app官网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值