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


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

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";


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM