template模塊主要是展示,方法需要在使用template的頁面中定義,對於通用的數據,最先想到或者理應是template,但是template有個缺點,那就是只是頁面效果,不會有對應的js操作。
而component組件,則擁有自己的js文件,整個component組件類似一個page頁面。簡單來說,只是展示用,建議使用template,組件中涉及到較多的邏輯,建議使用component。
一、template模塊
定義模板,一份template.wxml文件中能寫多個模板,用name區分
<template name="easy"> <text class='red' bindtap="click">I'm Easy,{{hello}}</text> //注意:1、這里有個點擊事件。2、{{hello}}是使用模板時傳入的屬性(參數) </template> <template name="Davi"> <text>I'm Davi,nice to meet you</text> </template>
在頁面中引入並使用模板
<!--index.wxml--> //導入模板 <import src="../../template/template.wxml" /> <view class="container"> <!-- 引用template模板,用is="easy"的方式,選擇模板 --> <template is="easy" data="{{...str}}" /> //傳入參數,必須是對象 <template is="Davi" /> </view>
在頁面中引入模板樣式。模板擁有自己的樣式文件(用戶自定義),只需要在使用頁面的wxss文件中引入即可
/**index.wxss**/ @import "../../template/template.wxss"; //引入template樣式 .container{ display:flex; }
由於template中沒有js文件,因此template中的點擊事件,在使用頁面中的js里定義。如上,name=easy的模板有個點擊事件click,則click方法,需要在index.js中定義
//index.js Page({ data: { str:{ hello:”nice to meet you“ } }, click:function(){ console.log("click Easy"); } })
因為template沒有自己的js文件,所以在列表中涉及到列表子項獨立的操作,建議將列表子項寫成component。
二、component組件
小程序組件文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/
創建一個component,只需要在其目錄下右鍵--新建--component,即可直接生成4個文件(json中的設置會默認"component": true)。component組件的結構和page的結構類似,都是有js、wxml、wxss、json四類文件組成。wxss代碼與page是一樣的,代碼就不貼了。其他代碼如下:
wxml代碼,與page一樣
<!--components/hello/hello.wxml--> <text class="red" bindtap="click">component {{type}} hello {{name}}</text>
js代碼,與page有些許不同
// components/hello/hello.js Component({ /** * 組件的屬性列表,使用組件時,傳入的參數 */ properties: { name:{ type:String, value:'' } }, /** * 組件的初始數據,組件內部的數據 */ data: { type:"組件" }, /** * 組件的方法列表,組件內部的方法 */ methods: { click:function(){ console.log("easy"); } } })
json代碼,需要注明"component": true,表示這是一個組件
// components/hello/hello.json
{
"component": true,
"usingComponents": {}
}
page中的使用,與template模板不同,component不需要在wxml中引入,但需要在json中指明使用的組件名及路徑。
<!--index.wxml--> <view class="container"> <hello name="Easy"/> //使用hello組件,並傳入值為“Easy”的name屬性(參數) </view>
//index.json
{
"usingComponents":{
"hello":"/components/hello/hello" //前面的hello是組件名,可以更改。路徑指向使用的組件
}
}