设置值时最好用
this.setData({
posts_key:postsData.postList
});
取值时可以用 this.data.posts_key
1.简单模拟服务器加载数据过程(数据分离)
新建目录data,创建post-data.js,把数据复制过来(表示从服务器加载的数据)
给脚本文件定义一个出口:
module.exports = {
postList: post_content
}
在post.js最上面定义
var postData =require("../../data/post-data.js") 必须是相对路径
onLoad: function (options) {
this.setData({ post_key: postData.postList});
}
post_key:是wxml文件中<block wx:for="{{post_key}}">要用到的名字
postData是var postData =require("../../data/post-data.js")中定义的名字
postList是出口postList: post_content中定义的名字。
代码:
post-data.js
var post_content = [
{
数据1
},
{
数据2
},
{
数据3
},
{
数据4
},
]
module.exports = {
postList: post_content
}
post.js
var postData =require("../../data/post-data.js")
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({ post_key: postData.postList});
},
})
小程序读取data对象来做数据绑定,这个行为是在onLoad事件之后执行的
2.template模板
wx:for只能在当前页面循环,无法跨页面
在post项目中创建post-item项目,创建post-item-template.wxml和post-item-template.wxss(js文件有效)
将模板代码复制到post-item-template.wxml中用<template name="postItem"></template> 包裹
引入模版:在post.wxml中最上面 <import src="post-item/post-item-template.wxml"/>(可以绝对路径)
在需要引入模版的地方 <template is="postItem" data="{{item}}"/> 即可
is="postItem" 是模版的名字:<template name="postItem"></template>
data="{{item}}“指postList中的子元素 如果想要把item.data的item去掉,只需data="{{...item}}"展开数据
样式:把需要的样式拷入wxss文件中
@import "post-item/post-item-template.wxss" 即可
代码:
post-item-template.wxml
<template name="postItem">
<view class="post-container">
<view class="post-title">
<image src="{{item.photo}}"></image>
<text>{{item.date}}</text>
</view>
<image class="post-image" src="{{item.url}}"></image>
<text class="post-content">
{{item.text}}
</text>
</view>
</template>
post.wxml
<import src="post-item/post-item-template.wxml"/>
<view>
<swiper indicator-dots='true' autoplay='true' vertical='{{false}}'>
<swiper-item>
<image src="/images/1.jpg"></image>
</swiper-item>
<swiper-item>
<image src="/images/2.jpg"></image>
</swiper-item>
<swiper-item>
<image src="/images/3.jpg"></image>
</swiper-item>
<swiper-item>
<image src="/images/4.jpg"></image>
</swiper-item>
</swiper>
<block wx:for="{{post_key}}">
<template is="postItem" data="{{item}}"/>
</block>
</view>
post-item-template.wxss 只有模版的样式
posy.wxss
@import "post-item/post-item-template.wxss"
swiper{
height: 500rpx;
width: 100%;
}
swiper image{
height: 500rpx;
width: 100%;
}
3.文章详情页面(模版中的点击事件以及获取当前点击的事件)
post目录中创建post-detail目录,创建各类文件 (新建一个网页就要记得在app.json中配置)
点击响应事件:不能加在post.wxml中<template>标签上,因为模板生成以后,这个标签根本不存在,
所以要用一个view标签把<template>进行包裹,在view标签上进行事件绑定
<view catchtap='onPostTap'>
<template is="postItem" data="{{item}}"/>
</view>
定义函数 onPostTap
在post.js中
onPostTap:function(){
wx.navigateTo({url:"post-detail/post-detail"})
},
点击不同的文章跳转不同的页面,明天再学~