小程序中模板的使用
1,定义模板和样式,
注意:小程序只是是实现了模板的功能,但是没有实现模块的功能,所以这里不能定义js,即使有js也不会执行
template name='postItem' !--name表示模板的名字-- view class='post-container' xxxxxx /view/template使用:
使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:
import src='post-item/post-item-template.wxml'/view class='body' template is='postItem' data='{{...item}}'/ !--is后是模板的名字-- !--{{...item}}三个点表示展开当前这个对象的属性,这样做的好处就是模板里不需要再写这个对象的名字。直接使用属性名--/viewis 属性可以使用 Mustache 语法,来动态决定具体需要渲染哪个模板:
template name="odd" view odd /view/templatetemplate name="even" view even /view/templateblock wx:for="{{[1, 2, 3, 4, 5]}}" template is="{{item % 2 == 0 ? 'even' : 'odd'}}"//block样式也要引入
@import 'post-item/post-item-template.wxss';swiper{ width:100%; height:600rpx}swiper image{ width:100%; height:600rpx}获取模板中的数据
有时候我们需要用户点击了模板中的什么数据,如果直接把事件写在template上,会发现事件不会被触发,甚至页面上也不存在这个template标签
template is='postItem' data='{{...item}}' bind:tap="test" /原因:template是相当于占位符,页面渲染后已经不存在了,所以不能再上面绑定事件,如果有需要可以在template外边包裹一层view,把事件加到view上面
block wx:for="{{[1, 2, 3, 4, 5]}}" view class='body' data-id='{{item.id}}' bind:tap="test" template is='postItem' data='{{...item}}'//view/blockjs
test:function (event){ console.log(event.currentTarent.dataset.id) //这里dataset表示所有自定义属性的对象 //参数名使用中横线,横线前的首字母会自动大写,如果参数名中有大写字母又不是在中横线后的第一个字母,会自动小写}













