【微信小程序-原生开发】实用教程16 - 查看详情(含页面跳转的传参方法--简单传参 vs 复杂传参)

需在实现列表的基础上开发

【微信小程序-原生开发】实用教程15 - 列表的排序、搜索(含云数据库常用查询条件的使用方法,t-search 组件的使用)_朝阳39的博客-CSDN博客
https://sunshinehu.blog.csdn.net/article/details/129356909

效果预览

在这里插入图片描述

技术要点

详情的获取有两种方式:

方式一:通过 id 获取详情

优点:可以确保每次打开详情都是最新的内容
缺点:需要访问详情接口,会消耗调用次数和客户流量

以查看成员详情为例

在这里插入图片描述

    <t-cell url="{
     
     {'/pages/components/friend/detail/index?id='+item.memberID}}" align='top' leftIcon="user-add" wx:if="{
     
     {item.type === 3}}" title="{
     
     {'热烈欢迎 '+item.publisher+' 加入DOS圆梦大家庭!'}}" />
  • t-cell 组件的 url 属性可以直接实现页面跳转,效果同 wx.navigateTo

当然,也可以绑定点击事件,触发页面跳转

bindtap="gotoDetail" data-detail="{
    
    {item}}"
    gotoDetail(e) {
    
    
      let memberID = e.currentTarget.dataset.detail._id
      wx.navigateTo({
    
    
        url: '/pages/components/friend/detail/index?id='+ memberID
      })
    }

以上为在目标页面路径后添加参数的方式,实现页面传参,仅适用于参数内容少,且为字符串等基础数据类型的参数。(若是对象等复杂类型则不适合此种方式的页面传参)

详情页接收参数并查询详情

在页面生命周期 onLoad 方法中,接收来自上个页面通过页面路径传来的参数

onLoad(options) {
    
    
    // 通过id获取详情
    let id = options.id
    if (id) {
    
    
      this.setData({
    
    
        id: id
      })
      this.getDetail()
      return
    }
}
  getDetail() {
    
    
    let that = this
    that.setData({
    
    
      show: false
    })
    wx.showLoading({
    
    
      title: '加载中',
    })
    db.doc(this.data.id).get().then(res => {
    
    
      that.setData({
    
    
        detail: res.data,
        show: true
      })
      wx.hideLoading()
    }).catch(() => {
    
    
      that.setData({
    
    
        show: true
      })
      wx.hideLoading()
    })
  },

方式二:直接从列表传递详情

优点:无需访问接口,可节省调用次数和客户流量
缺点:查看的内容为获取当前列表时得到的详情内容,可能已不是最新的数据内容。

当页面跳转需传递复杂参数(如对象)时,则需采用以下方式

    gotoDetail(e) {
    
    
      let detail = e.currentTarget.dataset.detail
      wx.navigateTo({
    
    
        url: '/pages/components/friend/detail/index',
        success: function (res) {
    
    
          res.eventChannel.emit('sendData', {
    
    
            data: detail
          })
        }
      })
    }

详情页接收此种参数的方法如下:

  onLoad() {
    
    
    let that = this
    // 接收列表页传入的复杂数据--对象(详情)
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('sendData', function (res) {
    
    
      that.setData({
    
    
        id: res.data._id,
        detail: res.data,
        show: true
      })
    })
  },

猜你喜欢

转载自blog.csdn.net/weixin_41192489/article/details/129363447