微信小程序 跳转传值实现方式


无论小程序,还是安卓开发,列表点击跳转传值是必备掌握的基础知识。

跳转传值有多种方式,1.可以单穿某个字段,2.可以传对象。

这里我只讲下怎么传递对象,在实际开发中,传对象是普遍选择的一种传值方式。

下面是一个类表展示的数据

  <block wx:for="{{postData}}" wx:key="item" wx:for-index="index">
    <!-- is表示定义的模板名称 data为数据集合的item,微信小程序默认一条数据为 item -->
    <view bindtap='onItemonTap' id='{{index}}'>
      <template is="postItem" data="{{...item}}"></template>
    </view>
  </block>

分析:
1.列表的点击事件,最重要的是如何获点下对应item的position 下标。
定义一个下标:通过wx:for-index="index",并指定<view id="{{index}}"/>

6654721-74ce2457c1e601a7.png
yhx.png

2.通过定义好的下标index获取对象。
获取方式:event.currentTarget.id
再通过:JSON.stringify() 得到let;

//列表点击事件
 onItemonTap: function(event) {
   //获取点击item获取下标 
   var position = event.currentTarget.id;
   //获取item数据,将对象转String 
   //posts.postUtilsData[postId] 通过下标得到集合数据item
   let json = JSON.stringify(posts.postUtilsData[position])
   //跳转传值
   wx.navigateTo({
     url: '../../../post-detail/post-detail?dataObject=' + json,
   })
 }

3.怎么接收?
let item = JSON.parse(options.dataObject);

dataObject参数是跳转url 定义的,类似一般的get请求格式,不多说

 /**
   * 生命周期函数--监听页面加载
   * 接收参数,并设置数据
   */
  onLoad: function (options) {
    let item = JSON.parse(options.dataObject);
    this.setData({
      info:item
    })
  },

最后总结一下:

列表点击传递数据有很多种,这里我利用微信默认wx:for-index="index" 来指定下标。

第二种方式:

也可以通过自定义属性来指定下标data - xxxx

6654721-f19f3e5bebdcd37c.png
yhx.png

再获取: event.currentTarget.dataset.postid

6654721-482d7fdec32b6ae6.png
Image.png

传递多个参数:就是一个url路劲拼接而成

wx.navigateTo({
      url: '../../../post-detail/post-detail?dataObject=' + json + "&position=" + position,
    })

猜你喜欢

转载自blog.csdn.net/weixin_33798152/article/details/87211946