微信小程序模板之template

    技术2023-12-24  64

    1. 创建 template 模版

    template 模版 主要用于展示,模版中不涉及事件处理, 需要处理的事件逻辑放在调用模版的页面中。 一个 template 模版 只包含 wxml wxss 文件,建议文件命名以template结尾

    template.wxml 文件语法

    以渲染数据为多个数组为例:

    <template name="postItem"> <view class="post-container"> <image src="{{imgSrc}}" class="post-author"></image> <text class="post-data">{{date}}</text> </view> </template>

    2. 引用 template 模版

    template 模版的引用需要使用 <import/> 标签。 该标签的 src 属性 为需要引用模版的路径。template 模版的使用用 <template/> 标签。 使用 is 属性来区别模版文件中定义的模版。使用 data 传入模版中的数据。

    注意:引入标签需要闭合否则无法渲染;

    a 引入页面wxml

    <block wx:for="{{postsData}}" wx:for-item="item" wx:key="author"> <template is="postItem" data="{{...item}}"/> </block>

    注意:此处传入的data为vx-for-item 函数中的item …为ES6中对象的剩余操作

    b 引入页面wxss @import "url";

    注意:此处传入的url应为相对路径

    3绑定事件

    添加一个额外标签代理事件

    <block wx:for="{{postsData}}" wx:for-item="item" wx:key="author"> <view bind:tap="onPostTap"> <template is="postItem" data="{{...item}}" /> </view> </block>
    Processed: 0.020, SQL: 10