官方的文档如下:
之前看了好久,都不明白item是什么意思,然后一直手动使用{{array[0|1|2|3|4].message}}的原始方法将数据绑定起来,后来才知道item只是一个变量名,用来获取array数组里面的元素。
那么结合我的案例,当我们获取的json数据形如:
[{“name”:"小明",“age”:"18",“phone”:"1234"},{“name”:"小红",“age”:"22",“phone”:"4321"},...........{“name”:"小青",“age”:"16",“phone”:"6654"}]
则我们的js文件中的data这么定义即可:
data:{
personInfo: [{“name”:"小明",“age”:"18",“phone”:"1234"},{“name”:"小红",“age”:"22",“phone”:"4321"},{“name”:"小青",“age”:"16",“phone”:"6654"}]
},
然后加入你的wx.request方法:
wx.request({
url: '填入你获取json的地址url',
headers: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' },
//获取成功
success: function (res) {
console.log(res.data);
that.setData({
personInfo: res.data
})
},
//获取失败
fail:function(){
console.log("数据获取失败");
},
);
wxml文件:
在父视图容器中加入wx:for={{personInfo}},然后在子控件用{{item.name}}绑定数据即可,例如
<view class="parentcontent" wx:for="{{personInfo}}" wx:key='id'>
<view class="content" >{{item.name}}</view>
<view class="content" >{{item.age}}</view>
<view class="content" >{{item.phone}}</view>
</view>
这样,就把这json中的小明。小红,... ... 小青等以及他们的name,age,phone等信息数据循环展示出来了。