博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
微信小程序(三):使用template模板时无法获取for循环下标index的问题
阅读量:4106 次
发布时间:2019-05-25

本文共 2194 字,大约阅读时间需要 7 分钟。

使用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

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

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;}

 

转载地址:http://qlssi.baihongyu.com/

你可能感兴趣的文章
iOS之AFNetworking
查看>>
iOS之AFNetworking
查看>>
iOS之二维码扫描
查看>>
iOS之NSURLConnection
查看>>
iOS之AFNetworking3.0
查看>>
Leetcode Next Permutation
查看>>
leetcode Trapping Rain Water
查看>>
英才网编程
查看>>
名企与iOS第三方框架
查看>>
iOS REST服务
查看>>
iOS 再说缓存
查看>>
leetcode Valid Number
查看>>
IP 回顾
查看>>
SDL显示图像和文字
查看>>
面向对象的三大特征
查看>>
MFC框架程序中OnIdle
查看>>
代码编译过程
查看>>
函数调用规范
查看>>
关于VS中静态调用dll的一些问题
查看>>
C++:公有继承、私有继承和保护继承
查看>>