1. 程式人生 > >小程序自定義模板的正確使用方式

小程序自定義模板的正確使用方式

問題: 展開 pla mar HR javascrip 自定義模板 多個 item

最近在做小程序項目開發,遇到一些公用的模塊就順便使用了自定義的模板,渲染模板數組的時候遇到了一些問題:

template.wxml

<template name="primary">
  <button class=‘btn-class‘ type=‘primary‘>{{button.con}}</button>
</template>
<template name="warn">
  <button class=‘btn-class‘ type=‘warn‘>{{button.con}}</button>
</template>

單個模板文件,可以定義多個template,只需用name區分即可
index.wxml

<import src="../../component/template/button.wxml"/>
<block wx:for="{{buttonList}}" wx:key="unique">
   <template wx:if="{{index%2===0}}" is="primary" data="{{...item}}"></template>  
   <template wx:else is="warn" data="{{...item}}"></template>  
 </block>

通過使用es6的展開運算符...,代替item.button

模板的樣式可以在模板.wxml同級目錄書寫,通過在app.wxss中 *@import* 全局引入,這樣可以避免在每一個需要模板的地方都引入模板wxss文件。

/**app.wxss**/
@import "component/template/button.wxss";

小程序自定義模板的正確使用方式