
1 <template name="demo"> 2 <view class='tempDemo'> 3 <text class='name'>FirstName: {{firstName}}, LastName: {{lastName}}</text> 4 <text class='fr' bindtap="clickMe" data-name="{{'Hello! I am '+firstName+' '+LastName+'!'}}"> clcikMe </text> 5 </view> 6 </template>
3. 樣式文件:
模板擁有自己的樣式文件(用戶自定義)。
1 /* templates/demo/index.wxss */ 2 .tempDemo{ 3 width:100%; 4 } 5 view.tempDemo .name{color:darkorange}
4. 頁面引用:
page.wxml
1 <!--導入模板--> 2 <import src="../../templates/demo/index.wxml" /> 3 <!--嵌入模板--> 4 <view> 5 <text>嵌入模板</text> 6 <template is="demo" data="{{...staffA}}"></template><!--傳入參數,必須是對象--> 7 <template is="demo" data="{{...staffB}}"></template><!--傳入參數,必須是對象--> 8 <template is="demo" data="{{...staffC}}"></template><!--傳入參數,必須是對象--> 9 </view>
page.wxss
1 @import "../../templates/demo/index.wxss" /*引入template樣式*/
page.js
1 Page({ 2 /** 3 * 頁面的初始數據 4 */ 5 data: { 6 staffA: { firstName: 'Hulk', lastName: 'Hu' }, 7 staffB: { firstName: 'Shang', lastName: 'You' }, 8 staffC: { firstName: 'Gideon', lastName: 'Lin' } 9 }, 10 clickMe(e) { 11 wx.showToast({ title: e.currentTarget.dataset.name, icon: "none", duration: 100000 }) 12 } 13 ...... 14 })
備注:
一個模板文件中可以有多個template,每個template均需定義name進行區分,頁面調用的時候也是以name指向對應的template;
template模板沒有配置文件(.json)和業務邏輯文件(.js),所以template模板中的變量引用和業務邏輯事件都需要在引用頁面的js文件中進行定義;
template模板支持獨立樣式,需要在引用頁面的樣式文件中進行導入;
頁面應用template模板需要先導入模板 <import src="../../templates/demo/index.wxml" /> ,然后再嵌入模板 <template is="demo" data="{{...staffA}}"></template>
二. Component組件:
1. 組件創建:
新建component目錄——創建子目錄——新建Component;
2. 組件編寫:
新建的component組件也由4個文件構成,與page類似,但是js文件和json文件與頁面不同。
js代碼:
1 // components/demo/index.js 2 Component({ 3 /** 4 * 組件的屬性列表 5 */ 6 properties: { 7 name: { 8 type: String, 9 value: '' 10 } 11 }, 12 13 /** 14 * 組件的初始數據 15 */ 16 data: { 17 type: "組件" 18 }, 19 20 /** 21 * 組件的方法列表 22 */ 23 methods: { 24 click: function () { 25 console.log("component!"); 26 } 27 } 28 })
json配置文件:
1 { 2 "component": true, 3 "usingComponents": {} 4 }
3. 組件引用:
頁面中引用組件需要在json配置文件中進行配置,代碼如下:
1 { 2 "navigationBarTitleText": "模板demo", 3 "usingComponents": { 4 "demo": "../../components/demo/index" 5 } 6 }
然后在模板文件中進行使用就可以了,其中name的值為json配置文件中usingComponents的鍵值:
1 <demo name="comp" /> 2 <!--使用demo組件,並傳入值為“comp”的name屬性(參數)-->
這樣就可以了。
PS:組件中不會自動引用公共樣式,如果需要則需在樣式文件中引入:
1 @import "../../app.wxss";
個人原創博客,轉載請注明來源地址:https://www.cnblogs.com/xyyt/p/9559326.html