小程序中提供了模板功能,我们可以自定义一些模板,将一些多次重复使用的布局和样式定义成模板,比如商品列表之类的
步骤
- 创建模板
- 在页面中使用模板
项目结构及实现后效果
image.png
1、创建模板
goodsList.wxml 布局文件
goodsList.wxss 样式文件
goodsList.wxml —— 声明模板,并命名
// 声明这是一个名为goodsList 的模板
<template name="goodsList">
<view wx:for="{{goodsList}}" wx:for-item="goods" wx:key="unique">
<view class='goods-wrap'>
<view class='goods-img-wrap'>
<image src='{{goods.imgUrl}}' class='goods-img'/>
</view>
<view class='goods-info'>
<view class='goods-title'>
{{goods.title}}
</view>
</view>
</view>
</view>
</template>
goodsList.wxss
.goods-wrap{
display: flex;
margin-bottom: 20px;
}
.goods-img-wrap{
width: 80px;
height: 80px;
border-radius: 10px;
margin-right: 10px;
}
.goods-img{
width: 100%;
height: 100%;
border-radius: 10px;
}
.goods-info{
flex: 1;
}
.goods-title{
font-size: 14px;
color: #333333;
}
2、在页面中使用模板
index.wxml
index.wxss
index.js
index.wxml
// 引入模板
<import src="../template/goodsList/goodsList.wxml" />
<view class="container">
// 使用模板, 并将goodsList传入模板
<template is="goodsList" data="{{goodsList:goodsList}}"></template>
</view>
index.wxss —— 引入模板的wxss文件
@import "../template/goodsList/goodsList.wxss";
index.js
//index.js
Page({
data: {
// 定义goodsList
goodsList: [
{
imgUrl: 'https://ss1.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D220/sign=a35c76f9bade9c82b965fe8d5c8080d2/0824ab18972bd40704fe413d72899e510fb30930.jpg',
title: '这是第一个商品'
},
{
imgUrl: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1407465561,2169083741&fm=200&gp=0.jpg',
title: '这是第二个商品'
},
{
imgUrl: 'https://ss1.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D220/sign=a35c76f9bade9c82b965fe8d5c8080d2/0824ab18972bd40704fe413d72899e510fb30930.jpg',
title: '这是第三个商品'
},
{
imgUrl: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1407465561,2169083741&fm=200&gp=0.jpg',
title: '这是第四个商品'
},
]
},
onLoad: function () {
},
})
总结:
1、定义模板 <template name="goodsList"> </template>
2、使用模板
<import src="../template/goodsList/goodsList.wxml" />
<template is="goodsList" data="{{goodsList:goodsList}}"></template>
3、复用性高的布局样式才使用模板