大家好!最近一直在做小程序開發,也做了幾個項目,開發期間涉及到很多列表頁面,之前每次都是在每個頁面的wxml和wxss頁面寫了很多布局代碼,感覺一直在做重用功,為了盡量減少代碼量和后期維護的高效性,必須要走復用這步,查閱了很多資料,在這里記錄一下,同時希望對新手小伙伴有所幫助!
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>
listcell.wxss代碼無須貼出
其中 < 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"/>
復制代碼
在main.wxss文件里 導入
-
@import "../../template/listcell.wxss";
需要說一下: 如果項目需要大量使用一個模板,WXSS引入到全局(app.wxss 導入 @import “template/listcell.wxss”),減少代碼量;如果項目只是很少地方使用模板,可以在需要的頁面引入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>
通過template 標簽使用模板,template 標簽的 is 屬性與模板的 name 屬性對應,data 屬性代表傳入模板的數據
針對布局一樣,頁面不同內容不同傳參肯定不同,可直接在listcell里復制多個不同name的模板,修改參數即可。