1.数据分离
1.1模拟本地数据
1)在项目根目录创建data文件夹存放模拟数据文件posts-data.js
1.2导出本地数据
导出数据使用 module.exports = {}
1.3使用本地数据(某个页面)
1.3.1JS文件中使用
此例子中,由于是在postlist页面使用本地数据,
因此需要去postlist.js文件中操作数据导入和使用
1)require()导入数据
2)在onLoad生命周期绑定数据this.setData
// pages/postlists/postlist.js
//1)通过变量postData导入文件夹data/posts-data中的数据
var postData = require("../../data/posts-data.js");
//注意:
//console.log(typeof postData);//不加.postList取到数据最外层
//console.log(typeof (postData.postList));//加.postList可以取到里层数据
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//2)setData绑定导入数据
this.setData({
//导入数据为postData.postList,导入数据传值给contentList
//在postlist.wxml文件中,绑定数据为:{
{contentList}}
contentList:postData.postList
})
},
1.3.2在WXML中使用
1)在postlist.wxml中使用数据
2)在block标签中使用 wx:for =" " 进行列表渲染
3)wx:for="{
{contentList}}" 中使用花括号绑定 contentList
4)template标签中,增加data属性, 取值为 data="{
{…item}}" (注: 符号…为扩展运算符,使用后,模板文件中花括号绑定的数据不用添加 item. 前缀)
<!--pages/postlists/postlist.wxml-->
<!-- 通过import导入模板 -->
<import src="./post-template/post-template.wxml" />
<!-- 在WXML中使用数据{
{contentList}} -->
<block wx:for="{
{contentList}}" wx:for-item="item" wx:for-index=