小程序中提供了模板功能巷折,我們可以自定義一些模板崖咨,將一些多次重復(fù)使用的布局和樣式定義成模板,比如商品列表之類的
步驟
- 創(chuàng)建模板
- 在頁面中使用模板
項目結(jié)構(gòu)及實現(xiàn)后效果
image.png
1逊拍、創(chuàng)建模板
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 () {
},
})
總結(jié):
1骗露、定義模板 <template name="goodsList"> </template>
2血巍、使用模板
<import src="../template/goodsList/goodsList.wxml" />
<template is="goodsList" data="{{goodsList:goodsList}}"></template>
3、復(fù)用性高的布局樣式才使用模板