uniapp 页面跳转传值(eventChannel)

在A -> B页面时,如果想要将A页面中的数据传给B,可以使用eventChannel方法或者用url拼接,在这里先说明第一种eventChannel方法如何实现。

A页面:

首先定义了一个点击事件handleItemClick,触发点击事件后再传递数据

data() {
  return {
     itemData: '123' 
  }   
}

methods: {
  handleItemClick() {
      const _this = this
      uni.navigateTo({
        url: '/pages/productionSchedule/detail/index', //B页面的路由
        success(res) {
          res.eventChannel.emit('acceptDataFromDistributionGuidance', { data: _this.itemData})
        }
      })
    },
}

B页面:

  data() {
    return {
      orderInfo: {}
    }
  },

onLoad() {
    const eventChannel = this.getOpenerEventChannel()
    let orderInfo = {}
    // 监听acceptDataFromDistributionGuidance事件,获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromDistributionGuidance', function (data) {
      orderInfo = { ...data.data }  // data为接收到的数据
      console.log('$', data)
    })
    this.orderInfo = orderInfo
  },

注意:this指向

1.B页面中:

  如果是想要把接收到的数据存到B页面的data中,不能在on事件内部直接使用this,因为此时this指向并不是全局,而是函数内部,所以无法通过this.orderInfo = orderInfo语句赋值,在B页面中我通过在on外部重新定义了一个局部变量,先将传过来的数据赋值给局部变量,最后在on的外部通过局部变量赋值给data中的orderInfo

2.A页面中:

  在A页面中同样不能够通过this. itemData将data中的数据传给B,因为此时的this并没有指向全局,所以在外部重新定义了一个常量_this,它指向全局,在success回调函数中,用_this代替this实现将data中的数据传递给B页面

 

posted on 2023-06-15 16:18  zy89898976  阅读(748)  评论(0编辑  收藏  举报