简介
template在微信小程序中大大提高了代码的复用性。
一层template
对于普通的一层template在使用的时候,我们可以简单的通过以下方式进行赋值:
1、wxml中定义
<!-- 我的收藏的模版 -->
<template name="favourite">
<view class='vertical' style='flex:auto;align-items: center;'>
<text class='number'>{{no}}</text>
<text class='numbertip'>{{noTip}}</text>
</view>
</template>
2、wxml中使用
<template is="favourite" data="{{...favourite}}" />
注意前面要有'...'不能丢,否则将不会显示
3、在js文件中去设置该数据源的值。
data{
favourite: {
no: "0",
noTip: "我的收藏"
}
}
多层的template赋值
这种方式在用的时候,自己纠结了好长时间,没有找到合适的文章给自己提供思路。还好,自己瞎试出来。
1、wxml中定义
<template name="mine">
<view class='vertical' style='flex:auto;align-items:center;padding-top:40rpx;padding-bottom:40rpx;'>
<image src='{{imagePath}}' style='width:100rpx;height:100rpx;margin-bottom:30rpx; '></image>
<text class='number'>{{mine}}</text>
</view>
</template>
<template name="minerow">
<view class='horizontal' style='background-color:white; margin-top:30rpx;'>
<template is="mine" data="{{imagePath,mine}}"></template>
<view class='verticalline'></view>
<template is="mine" data="{{imagePath:imagePath1,mine:mine1}}"></template>
<view class='verticalline'></view>
<template is="mine" data="{{imagePath:imagePath2,mine:mine2}}"></template>
<view class='verticalline'></view>
<template is="mine" data="{{imagePath:imagePath3,mine:mine3}}"></template>
</view>
</template>
2、wxml中使用
<template is="minerow" data="{{...minerow11}}"></template>
3、在js文件中去设置该数据源的值
data{
minerow11: {
imagePath: "../../../resource/mine.png",
mine: "我的账户",
imagePath1: "../../../resource/mine.png",
mine1: "我的优惠券",
imagePath2: "../../../resource/mine.png",
mine2: "收货地址",
imagePath3: "../../../resource/mine.png",
mine3: "在线客服"
}
}
对比1和3中可以发现,其实关键在于可以通过
data="{{imagePath:imagePath2,mine:mine2}}"
这种方式给不同的template进行赋值。
最后效果图如下:
如果有其他方式,大家可以一起讨论下