欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序 Template詳解及簡(jiǎn)單實(shí)例

 更新時(shí)間:2017年01月05日 16:28:29   投稿:lqh  
這篇文章主要介紹了微信小程序 Template詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下

微信小程序 Template

模板

WXML提供模板(Template),可以在模板中定義代碼片段,然后在不同的地方使用。可以保證格式以及數(shù)據(jù)的相同。

1-定義模板

使用`<template name="tempName"></template>`標(biāo)簽定義模板,并將模板名稱命名為tempName,賦值給屬性name。在標(biāo)簽內(nèi)部,定義模板結(jié)構(gòu)。如下:

<!-- template.wxml -->
<!-- 
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
  <text> {{index}}: {{msg}} </text>
  <text> Time: {{time}} </text>
 </view>
</template>

2-使用模板

使用<template is="tempName" />標(biāo)簽,在需要使用模板的地方。如果要用到j(luò)s文件中的數(shù)據(jù),則需要添加data屬性。如下:

<!-- template.wxml -->

<template is="msgItem" data="{{...item}}"/>
<template is="msgItem" data="{{...item}}"/>
<template is="msgItem" data="{{...item}}"/>
此時(shí)在頁(yè)面上就會(huì)重復(fù)顯示三次相同的信息。
data中的數(shù)據(jù),來(lái)源于js文件,如下:

<!-- template.js -->
Page({
 data: {
  item: {
   index: 0,
   msg: 'this is a template',
   time: '2016-09-15'
  }
 }
})

3-is屬性

is屬性不僅可以靜態(tài)的指向渲染的模板,也可以使用Mustache語(yǔ)法,來(lái)動(dòng)態(tài)決定具體需要渲染哪個(gè)模板。如下:

<!-- template.wxml -->

// templates
<template name="odd">
  <view> odd </view>
</template>
<template name="odd">
  <view> even </view>
</template>

// is屬性使用Mustache語(yǔ)法動(dòng)態(tài)渲染template
<block wx:for="{{[1, 2, 3, 4,5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}" />
</block>

如上代碼,則會(huì)在頁(yè)面中根據(jù)條件來(lái)顯示odd 或是 even

4-模板的引用

如上都是在同一個(gè)wxml文件中定義和引用模板,而模板的定義和引用是可以分開(kāi)的。即在一個(gè)文件中定義模板,而在其他一個(gè)或多個(gè)文件wxml文件中都可以使用定義好的模板。
從外部文件中引用模板,使用import src="templateUrl" />標(biāo)簽。同樣使用is屬性來(lái)指向要引用的標(biāo)簽。
如目錄如下:

-pages
  |--index
    |--index.js
    |--index.json
    |--index.wxml
    |--index.wxss
  |--template
    |--template.js
    |--template.json
    |--template.wxml
    |--template.wxss

要在index.wxml中使用template中定義的模板,則需要先在index中利用import來(lái)導(dǎo)入該模板:

<!-- index.wxml -->
<import src="../template/template.wxml"
<template is="msgItem" data={{...indexData}}
// 使用的是自己js文件中的數(shù)據(jù)

要注意import作用域,其僅僅引用目標(biāo)文件中template。如:C import B,B import A,在C中可以使用B定義的template,在B中可以使用A定義的template,但是C不能使用A定義的template。

參考

微信小程序文檔-框架-視圖層-WXML-模板

微信小程序文檔-框架-視圖層-WXML-引用

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論