參考了一系列的小程序UI庫。。。,最后參考了ant-design的折疊面板(collapse)組件設計,功能大致如下
折疊面板組件由列表組件(ui-list)實現,列表項作為標簽頁,列表項子元素 content 作為彈出層,數據子項結構大致如下
{ title: '標簽標題', content: '彈層內容' } 復制代碼
構建一個動態組件 ui-list ,通過配置文件實現列表結構,將如下這段數據結構
const mockData = [ {title: '列表項1', content: '彈層內容1'}, {title: '列表項2', content: '彈層內容2'}, {title: '列表項3', content: '彈層內容3'}, ] 復制代碼
生成大致如下的wxml
<view class="list-container"> <view class="item"> <view class="title">列表項1</view> <view class="content">彈層內容1</view> </view> <view class="item"> <view class="title">列表項2</view> <view class="content">彈層內容2</view> </view> <view class="item"> <view class="title">列表項3</view> <view class="content">彈層內容3</view> </view> </view> 復制代碼
通過css樣式,將彈層內容 <view class="content"> 隱藏
<view class='title'> 作為展示標簽,也作為點擊事件的主體,當點擊標簽時為 <view class='item'> 的子容器添加 active 激活樣式,此時彈層內容通過樣式設計為 display: block 狀態,即實現彈出顯示
<view class="item active"> <view class="title" bind:tap="change">列表項1</view> <view class="content">彈層內容1</view> <!--css display block--> </view> 復制代碼
為標簽點擊時提供 changeTitle,changeContent 方法,通過關鍵字段尋址,并更新數據,從而更新wxml結構,如下列的思路
<view class="title" bind:tap="change" data-index="1">列表項1</view> 復制代碼
change(e){ const ds = e...dataset this.toggleActive(e) this.changeTitle(ds, ...) // 或者 this.changeContent(e, ...) } changeTitle(ds, param) { let index = ds.index let $data = findIt(index) $data.title = param this.setData({config.data[index]: ....}) } changeContent(ds, param) { // 思路同changeTitle } 復制代碼
上面所述是簡化邏輯,實現起來并不如此簡單,尤其是尋址邏輯和更新邏輯
<ui-list wx:if="{{collapsConfig}}" list="{{collapsConfig}}" /> 復制代碼
let config = { listClass: 'collapse-pad', data: [], tap: function(param){ // 切換響應方法,樣式操作封裝在組件內部 // this.title({...}) // this.content({...}) // this.disabled(true|false) } } Page({ data: { collapsConfig: config } }) 復制代碼
動態標簽的好處是可以將邏輯、尋址等在JS部分來實現,相較于 template 語法,動態標簽的方式靈活太多了,能方便的實現組件化、模塊化,規范化,和將公共部分抽離,且易于維護。當一個項目有多人維護時,碎片模板是一個地獄。