微信小程序实现列表复用
大家好!最近一直在做小程序开发,也做了几个项目,开发期间涉及到很多列表页面,之前每次都是在每个页面的wxml和wxss页面写了很多布局代码,感觉一直在做重用功,为了尽量减少代码量和后期维护的高效性,必须要走复用这步,查阅了很多资料,在这里记录一下,同时希望对新手小伙伴有所帮助!
1.首先我们创建一个template模板文件夹 创建2个文件 listcell.wxml 和 listcell.wxss
2.然后我们在listcell.wxml里创建自己的cell ,直接上代码
其中 < template name=“list” > 中name为该模板的名称,在调用的时候,可根据不同的name来引用自己需要的模板。
这里需要说一下,布局相同的列表页面cell都放在listcell.wxml里即可,因为布局一样 ,共用一套wxss。布局不相同的列表页面cell 按照个人习惯了,也可以放在listcell.wxml里写 也可以再创建一个新的文件去写,所有不同布局的cell都放到一个listcell.wxml里写的话,wxss里代码会非常多,看起来不是很清晰。
3.调用template模板
在需要调用的列表页面,引入模板文件头文件
在main.xml文件里 这样导入
在main.xml里列表view中设置模板
针对布局一样,页面不同内容不同传参肯定不同,可直接在listcell里复制多个不同name的模板,修改参数即可。

1.首先我们创建一个template模板文件夹 创建2个文件 listcell.wxml 和 listcell.wxss
2.然后我们在listcell.wxml里创建自己的cell ,直接上代码
- <template name="list">
- <view class="notify-object">
- <view class='hengxiang1'>
- <image class='cellnotifyImage' data-index="{{index}}" src="../../images/notify1.png" />
- <view class='shuxiang1'>
- <text class=' textblackColor sunFont10 textsub1'>{{item.titleName}}</text>
- <text class=' textblackColor70 sunFont8 textsub1'>{{item.profile}}</text>
- <text class=' textblackColor97 sunFont8 textsub2'>{{item.time}}</text>
- </view>
- </view>
- </view>
- </template>
- <template name="list1">
- <view class="notify-object">
- <view class='hengxiang1'>
- <image class='cellnotifyImage' data-index="{{index}}" src="../../images/notify1.png" />
- <view class='shuxiang1'>
- <text class=' textblackColor sunFont10 textsub1'>{{item.title}}</text>
- <text class=' textblackColor70 sunFont8 textsub1'>{{item.phone}}</text>
- <text class=' textblackColor97 sunFont8 textsub2'>{{item.date}}</text>
- </view>
- </view>
- </view>
- </template>
其中 < template name=“list” > 中name为该模板的名称,在调用的时候,可根据不同的name来引用自己需要的模板。
这里需要说一下,布局相同的列表页面cell都放在listcell.wxml里即可,因为布局一样 ,共用一套wxss。布局不相同的列表页面cell 按照个人习惯了,也可以放在listcell.wxml里写 也可以再创建一个新的文件去写,所有不同布局的cell都放到一个listcell.wxml里写的话,wxss里代码会非常多,看起来不是很清晰。
3.调用template模板
在需要调用的列表页面,引入模板文件头文件
在main.xml文件里 这样导入
- <import src="../../template/listcell.wxml"/>
- @import "../../template/listcell.wxss";
在main.xml里列表view中设置模板
- <view class='sencondviewback2' style="height: {{screenHeight-315}}px;">
- <scroll-view scroll-y style="height: {{screenHeight-315}}px;">
- <template wx:for="{{notifyListData}}" is="list" data="{{item}}"></template>
- </scroll-view>
- </view>
针对布局一样,页面不同内容不同传参肯定不同,可直接在listcell里复制多个不同name的模板,修改参数即可。