定义 template 模板
为了方便代码组织,我们在 templates 目录下,新建一个
productCard 文件夹,并在 product-card 文件夹下新建 productCard.wxml 和 productCard.wxss 文件。
代码如下:
<template name="productCard"> <view class="product-card">
<navigator url="../detail/detail?id={{ id }}">
<view style="background-image: url({{ cover_image }})" class="product-cover"> </view>
<view> <text
class="product-title">{{ title }}</text>
<text class="product-price">
¥{{ price }}</text>
</view>
</navigator>
</view>
</template>
使用 name 属性,定义模板的名字,然后将代码片断保存在 template 中。
- 引入 template 模板
以首页为例,当要使用到 productCard 模板时,我们只需要使
用 import 引入模板。
在需要显示的位置,外层用 wx:for 循环渲染列表,template
为子项,使用 is 声明需要的使用的模板,用 data 传入数据:
/*** index.wxml ***/
<import src="../../templates/productCard/productCard.wxml " />
<view class="product-list">
<block wx:for="{{ productNewList }}" <template
is="productCard" data="{{ ...item }}" /> </block>
</view>
留意 data="{{ ...item }} 的写法,item 是 wx:for 中 代表数组当前项的默认变量名,item 前面的 ... 操作符相当于 ES6 中的展开运算符,可用于需要解构赋值的地方,没有了解过展开 运算符和解构(Destructuring)的同学可以先了解一下它们的基本概 念。
通过解构,template 中就可以直接写成 {{ id }}, {{ cover_image }},而不用写 {{ item.id }}, {{ item.cover_image }}。
它的意义在于实现了 template 与 wx:for-item 之间的解 耦,比如这里设置了 wx:for-item="product",我们只要设改变
data="{{ ...product }}" 就可以了。 如果数据没有通过解构,就要将 template 的 {{ item.id }}
修改成 {{ product.id }},很不方便。
WXML 引用
import 可以在当前文件中使用目标文件定义的 template
在 item.wxml 中定义了一个 item 的 template
<!-- item.wxml -->
<template name="item">
<text>{{text}}</text>
</template>
在 index.wxml 中引用 item.wxml,就可以使用 item 的模板
<import src="item.wxml"/>
<template is="item" data="{{text: 'forbar'}}"/>
网友评论