小程序(四)数据绑定及列表渲染
2019-01-14 本文已影响0人
小狐狸ry
数据绑定
WXML 中的动态数据均来自对应 Page 的 data。现在我们在onLoad:function (options){}
函数中加入数据,假设是动态获取到的,来学习数据绑定。
在js文件中输入 Page 回车,Page(object)构造器就被调用出来了。
newslist.js
onLoad: function (options) {//假设下面的数据是动态获取到的
var post_content1 = {
date: "Sep 18 2016",
title: "比利·林恩的中场故事",
post_img: "/images/post/bl.png",
author_img: "/images/avatar/2.png",
content: "一“李安是一位绝不会重复自己的导演,本片将极富原创性李安”",
view_num: "112",
collect_num: "96"
}
this.setData(post_content1); //把post_content1的内容传递到data{}中
}
newslist.wxml
<view class='post-container'>
<view class='post-author-date'>
<image class='post-author' src='{{author_img}}'></image>
<text class='post-date'>{{date}}</text>
</view>
<text class='post-title'>{{title}}</text>
<image class='post-image' src='{{post_img}}'></image>
<text class='post-title'>{{content}}</text>
<view class='post-like'>
<image class='post-like-image' src='../../images/icon/chat.png'></image>
<text class='post-like-font'>{{view_num}}</text>
<image class='post-like-image' src='../../images/icon/view.png'></image>
<text class='post-like-font'>{{collect_num}}</text>
</view>
</view>
以上实现了基础数据绑定。
下面来说一下数据绑定的扩展:
在js文件中的 两个 图片路径我们可以写成:
img: {
post_img: "/images/post/bl.png",
author_img: "/images/avatar/2.png"
},
img_condition:true,//动态控制图片显隐,布尔类型
在wxml中获取数据时就要写成
<!-- wx:if 控制图片显隐 -->
<image wx:if="{{img_condition}}" class='post-author' src='{{img.author_img}}'></image>
关于小程序数据绑定的其他内容可以查看小程序开发文档
列表渲染
block wx:for
在组件上使用wx:for
控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。
默认数组的当前项的下标变量名默认为 index
,数组当前项的变量名默认为 item
使用 wx:for-item
可以指定数组当前元素的变量名,
使用 wx:for-index
可以指定数组当前下标的变量名:
<block wx:for="{{posts_key}}" wx:key="posts_key" wx:for-item="item" wx:for-index="idx">
<view class='post-container'>
<view class='post-author-date'>
<!-- wx:if 控制图片显隐 -->
<image class='post-author' src='{{item.author_img}}'></image>
<text class='post-date'>{{idx}} {{item.date}}</text>
</view>
<text class='post-title'>{{item.title}}</text>
<image class='post-image' src='{{item.post_img}}'></image>
<text class='post-title'>{{item.content}}</text>
<view class='post-like'>
<image class='post-like-image' src='../../images/icon/chat.png'></image>
<text class='post-like-font'>{{item.view_num}}</text>
<image class='post-like-image' src='../../images/icon/view.png'></image>
<text class='post-like-font'>{{item.collect_num}}</text>
</view>
</view>
</block>
好了开始测试吧 ^ _ ^