使用template模板渲染的数据列表,点击后跳转到详情页,本想通过for循环中的index对应点击的是哪一条数据,后来发现template模板中无法获取index。
问题重现:【接微信小程序(二)的示例继续写】
运行结果:
后来查阅资料发现template中无法获取下标index,那如何获取呢?
方法一:for循环的下标index不能直接在template中获取,需要通过template的data属性传入template。这里只能以data="{{item:item,index:index}}"的格式,我试过data="{{...item,...index}}"和data="{{...item,index:index}}"都行不通。
运行结果:能成功获取index
方法二:在js中手动为每条数据添加一个index
运行结果:也能成功获取
方法二的完整代码:
templateStudy.wxml
<import src="../student-item/student-item-template.wxml" />
<view class='container'>
<block wx:for="{{studentsList}}" wx:for-item="item" wx:for-index="index">
<view class='list' catchtap="onStudentTap" data-studentId="{{item.studentId}}">
<template is='studentTemplate' data="{{...item}}" />
</view>
</block>
</view>
templateStudy.wxss
@import "../student-item/student-item-template.wxss";
page{
background-color: #f0f0f0;
}
.container{
margin: 20rpx;
}
templateStudy.js
var postsData = require('../../../data/students.js')
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
for (var idx in postsData.studentsList) {
postsData.studentsList[idx].studentId = idx;
}
this.setData({
studentsList: postsData.studentsList
});
console.log(this.data.studentsList);
},
onStudentTap: function (event){
var idx = event.currentTarget.dataset.studentid;
console.log(idx);
wx.navigateTo({
url: "../studentDetail/studentDetail?id=" + idx
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
student-item-template.wxml
<template name='studentTemplate'>
<view class='list-item'>
<view class='title'>
<label class='username'>{{username}}</label>
</view>
<view class='info'>
<label class='classes'>{{classname}}</label>
<label class='Sno'>学号:{{Sno}}</label>
</view>
</view>
</template>
student-item-template.wxss
.list-item{
background-color: white;
border-radius: 10rpx;
}
.title{
margin: 20rpx;
line-height: 80rpx;
flex-direction: row;
display: flex;
border-bottom: 1rpx solid #f0f0f0;
}
.num{
position: absolute;
right: 50rpx;
}
.info{
margin: 20rpx;
flex-direction: row;
display: flex;
line-height: 60rpx;
font-size: 34rpx;
}
.Sno{
position: absolute;
right: 50rpx;
}