无论是百度小程序还是微信小程序,app.json中规定的tabbar页面是不支持传参的,例如:
<navigator url='../service/service?typeid=6' openType="switchTab">
服务项目
</navigator>
上面的navigater跳转有个属性:openType="switchTab"意思是打开tabbar页面service,虽然有个参数typeid=6,但是typeid=6并不能呗tabbar页面接收,造成打开tabbar页面的时候用于都是默认栏目。
(1)第一步:通过bindtap绑定方法触发缓存,把typeid存起来
虽然tabbar不支持传参,但是我们可以通过缓存的方式获取传递的参数,那么上面的navigator直接跳转的方式就不行了,需要封装一个方法:
<view class='service_li' bindtap='show_service' data-typeid='11' data-listtype='3'>
服务项目
</view>
index页面的“服务项目”通过bindtap绑定一个show_service方法,这个show_service会传递后边的data-*里边的所有参数。
在index.js中写上show_service方法:
show_service: function (e) { var data = e.currentTarget.dataset; var title = data.title; //获取传递的titlevar typeid = data.typeid; //获取传递的typeidvar listtype = data.listtype; //获取传递的listtype//通过setStorageSync方法将typed存入stypeid中,名字可以自己任意定wx.setStorageSync('stypeid', typeid) wx.switchTab({ //通过switchTab方法跳转到对应页面url: '/pages/service/service?typeid=' + typeid + "&title=" + title + "&listtype=" + listtype, //后边参数其实无效可以直接写成:‘/pages/service/service’}) },
这样我们就把用户点击首页所传递的参数typeid存到缓存里边了
(2)第二步:在service中去获取typeid
在service.js中的onload或者onshow中加入typeid的方法,为了兼容用户是直接通过tabbar进入的情况,需要一个默认的typeid,参考代码:
var stypeid = wx.getStorageSync('stypeid');//通过缓存获取typeid
var typeid = stypeid ? stypeid : that.data.typeid; //如果stypeid存在读取,否则读取默认的typeid
然后我们可以直接通过getList()方法直接读取api获取内容列表了
that.getList(typeid);
说明:
(1)如果你不是通过首页的show_service方法进入service页面的,那么就不会触发更新缓存,所以typeid的值是不会变的,通过点击tabbar进入service页面会永远显示某一个页面,你可以在onHide方法中增加一个重置或者情况stypied的方法,不过不建议这么弄
(2)service页面的切换栏目后,我们可以在switch_tab方法中加入修改缓存的方法,动态存入当前栏目的typeid
switch_cat: function (e) { var that = this; var CATEGORYS = wx.getStorageSync('categorys')//调用栏目缓存 var data = e.currentTarget.dataset; var typeid = data.typeid; var listtype = data.listtype; var curtypeid = data.typeid; that.setData({ curtypeid: curtypeid, listtype: listtype, page: 1 }) wx.setNavigationBarTitle({ title: CATEGORYS[curtypeid]['typename'] + '-' + wx.getStorageSync('system').seotitle }); that.getList(typeid); },