十一、歌手详情页的跳转传参
分析:这里使用通信通道wx.navitageTo()独有的进行传参,通过eventChannel向子页面“singerDetail”页面传送数据,
1、先在“热门歌手”里绑定bindtap事件,传递数据索引(见六),定义一个自定义事件hotlink在逻辑层通过一个函数来实现跳转,在block中设置,里面的view中引用就可以了。
<!-- 热门歌手 -->
<view class="title">热门歌手</view>
<view class="hotSinger">
<block wx:for="{{singer}}" wx:key="this" wx:for-index="gs">
<!-- 绑定自定义事件hotlink -->
<view class="item" bindtap="hotlink" data-index="{{gs}}">
<image src="{{item.picUrl}}"></image>
<text>{{item.name}}</text>
</view>
</block>
</view>
2、index.js拿到index.wxml中的自定义事件hotLink,像子页面(singerDetail.js)传参
// 点击跳转歌手详情页
hotlink:function (p) {
// 找到歌手的下标索引
const index = p.currentTarget.dataset.index;
// 拿到当前数据
const singer = this.data.singer
//传参
wx.navigateTo({
url: '../singerDetail/singerDetail',
// events:events,
success:(res)=>{
// 通过eventChannel把歌手的索引传给子页面
res.eventChannel.emit('acceptDataFromOpenerPage',{data:singer[index]})
},
})
},
点进去到子页面,控制台输出这些字样,就拿到首页传过来的东西了
3、在页面singerDetail.js中找到监听页面加载函数,通过acceptDataFromOpenerPage接收首页传来的数据
数据层定义singerData接收当前歌手的数据
data: {
// 当前歌手的数据
singerData:{}
},
// 这里接收主页传来的数据,并进行存储
onLoad: function(options) {
const eventChannel = this.getOpenerEventChannel()
eventChannel.on('acceptDataFromOpenerPage', data=>{
// 这里打印的就是父页面传来的数据
console.log(data)
this.setData({
// 把获取的data赋给上面定义的singerData{}
singerData: data
})
})
// 调用渲染页面的方法
this.getSingerDetail()
},
4、数据获取
getSingerDetail:function(){
// 这里打印的是上面数据层的data,即window下data的数据
//console.log(this.data);
var id = this.data.singerData.data.id
//console.log(id);
},
此时,歌手id就已经拿到了
5、以id为变量进行不同歌手的数据信息请求,并储存到geshouDetail:{}当中
wx.request({
url:'http://localhost:3000/artist/detail?id='+id,
dataType:'json',
method:'GET',
success:(res)=>{
// console.log(res.data.data)
this.setData({
// 储存数据
geshouDetail:res.data.data
})
}
})
},