利用模板動態加載數據,其實是對上一節靜態數據替換成動態數據:
template.wxml頁面代碼:
<!--pages/template/template.wxml--> <template name='listTmp'> <view class="tmpContainer"> <view class="avatar_date"> <image src="{{avatar}}"></image> <text>{{data}}</text> </view> <text class="user">{{title}}</text> <image class="contentImg" src="{{detail_img}}"></image> <text class="content">{{detail_content}} </text> </view> <view class="collection_love"> <image src="/static/images/star.png"></image> <text>{{love_count}}</text> <image src="/static/images/eye.png"></image> <text>{{attention_count}}</text> </view> </template>
template.wxml樣式代碼:
/* pages/template/template.wxss */
.tmpContainer{
display:flex;
flex-direction: column;
border-top:1rpx solid #eee;
border-bottom:1rpx solid #eee;
margin:10rpx 0;
}
.avatar_date{
padding: 10rpx;
}
.avatar_date image{
width:60rpx;
height:60rpx;
border-radius: 50%;
vertical-align:middle; /*解決基線對齊*/
margin-right: 10rpx;
}
.avatar_date text{
font-size:32rpx;
}
.user{
margin-left: 10rpx;
font-size: 36rpx;
font-weight: 700;
margin:10rpx;
}
.contentImg{
width:100%;
height:460rpx;
}
.content{
font-size:32rpx;
text-indent:64rpx;
}
.collection_love image{
width:32rpx;
height: 32rpx;
vertical-align: middle;
margin-left: 10rpx;
}
.collection_love text{
font-size:28rpx;
margin-left: 5rpx;
margin-right: 10rpx;
}
list.js增添部分內容:

代碼如下:
let datas=require('../data/list-data.js');
console.log(datas,typeof datas);
Page({
/**
* 頁面的初始數據
*/
data: {
listArr:[]
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {
this.setData({
listArr:datas.list_data
})
},
相對上一節增添的內容,用循環把數據遍歷出來:

代碼如下:
<block wx:for='{{listArr}}' wx:key='{{index}}'> <view> <template is='listTmp' data='{{...item}}'/> </view> </block>
