思路:
1.用wx.requext()获取数据
2.利用wx:for循环渲染
3.加入wx:if完成条件渲染
一:获取数据
在js中获取数据即可,在onLoad生命周期函数中请求
代码:
onLoad(options) {
//调用获取数据函数
this.getList();
},
//获取数据函数
getList(){
wx.request({
url: 'http://localhost:3000/data',//请求地址
method:"get",//请求的方法
success:(res)=>{//成功的返回值(注意:这里要用箭头函数要不然无法访问this);
console.log("res:",res);//{data: Array(10)....}
//修改保存数据的变量
this.setData({
list:res.data//list是在data中定义的变量
})
}
})
},
请求完成后可以在.wxml中使用
二:利用wx:for渲染
wx:for="{{list}}"中list是在data中定义的变量
wx:key="id" 唯一标识可以使用index但不建议使用
<view class="home-box">
<view class="home-item"
wx:for="{{list}}"
wx:key="id"
>
<text>姓名:{{item.name}}</text>
<text>年龄:{{item.age}}</text>
<text>性别:{{item.gender}}</text>
</view>
</view>
三.加入wx:if完成条件渲染
wx:if="{{item.gender==='男'}}":中{{item.gender==='男'}}是条件item为数组中的每一项item.gender为每一项中的性别,每一项中性别为男的数据才能渲染出来
<view class="home-box">
<view class="home-item"
wx:for="{{list}}"
wx:key="id"
wx:if="{{item.gender==='男'}}"
>
<text>姓名:{{item.name}}</text>
<text>年龄:{{item.age}}</text>
<text>性别:{{item.gender}}</text>
</view>
</view>
举一反三,根据不同的条件可以渲染出不同的数据.