小程序模板网

微信小程序实现列表复用功能

发布时间:2021-06-08 08:31 所属栏目:小程序开发教程
大家好!最近一直在做小程序开发,也做了几个项目,开发期间涉及到很多列表页面,之前每次都是在每个页面的wxml和wxss页面写了很多布局代码,感觉一直在做重用功,为了尽量减少代码量和后期维护的高效性,必须要走复用这步,查阅了很多资料,在这里记录一下,同时希望对新手小伙伴有所帮助!

 

1.首先我们创建一个template模板文件夹  创建2个文件 listcell.wxml 和 listcell.wxss

2.然后我们在listcell.wxml里创建自己的cell ,直接上代码
  1. <template name="list">
  2. <view class="notify-object">
  3. <view class='hengxiang1'>
  4.    <image class='cellnotifyImage' data-index="{{index}}" src="../../images/notify1.png" />
  5.    <view class='shuxiang1'>
  6.      <text class=' textblackColor sunFont10 textsub1'>{{item.titleName}}</text>
  7.      <text class=' textblackColor70 sunFont8 textsub1'>{{item.profile}}</text>
  8.      <text class=' textblackColor97 sunFont8 textsub2'>{{item.time}}</text>
  9.    </view>
  10. </view>
  11. </view>
  12. </template> 
  13. <template name="list1">
  14. <view class="notify-object">
  15. <view class='hengxiang1'>
  16.    <image class='cellnotifyImage' data-index="{{index}}" src="../../images/notify1.png" />
  17.    <view class='shuxiang1'>
  18.      <text class=' textblackColor sunFont10 textsub1'>{{item.title}}</text>
  19.      <text class=' textblackColor70 sunFont8 textsub1'>{{item.phone}}</text>
  20.      <text class=' textblackColor97 sunFont8 textsub2'>{{item.date}}</text>
  21.    </view>
  22. </view>
  23. </view>
  24. </template>
listcell.wxss代码无须贴出

其中 < template name=“list” > 中name为该模板的名称,在调用的时候,可根据不同的name来引用自己需要的模板。

这里需要说一下,布局相同的列表页面cell都放在listcell.wxml里即可,因为布局一样 ,共用一套wxss。布局不相同的列表页面cell 按照个人习惯了,也可以放在listcell.wxml里写 也可以再创建一个新的文件去写,所有不同布局的cell都放到一个listcell.wxml里写的话,wxss里代码会非常多,看起来不是很清晰。

3.调用template模板

在需要调用的列表页面,引入模板文件头文件
在main.xml文件里 这样导入
  1. <import src="../../template/listcell.wxml"/>

复制代码
在main.wxss文件里 导入
  1. @import "../../template/listcell.wxss";

需要说一下: 如果项目需要大量使用一个模板,WXSS引入到全局(app.wxss 导入 @import “template/listcell.wxss”),减少代码量;如果项目只是很少地方使用模板,可以在需要的页面引入WXSS。
在main.xml里列表view中设置模板
  1. <view class='sencondviewback2' style="height: {{screenHeight-315}}px;">
  2.    <scroll-view scroll-y style="height: {{screenHeight-315}}px;">
  3.    <template wx:for="{{notifyListData}}" is="list" data="{{item}}"></template>
  4.    </scroll-view>
  5. </view>
通过template 标签使用模板,template 标签的 is 属性与模板的 name 属性对应,data 属性代表传入模板的数据

针对布局一样,页面不同内容不同传参肯定不同,可直接在listcell里复制多个不同name的模板,修改参数即可。


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/26117.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询