相似於頁面,一個自定義組件由 json
wxml
wxss
js
4個文件組成css
首先須要在自定義組件所在的 json
文件中進行自定義組件聲明html
{ "component": true }
同時,還要在 wxml
文件中編寫組件模板,在 wxss
文件中加入組件樣式python
wxml與xcss和普通頁面設置差很少json
wxml小程序
<!-- 這是自定義組件的內部WXML結構 --> <view class="inner"> {{innerText}} <slot></slot> </view>
xcss微信小程序
/* 這裏的樣式只應用於這個自定義組件 */ .inner { color: red; }
js文件設置有點區別微信
Component({ properties: { // 這裏定義了innerText屬性,屬性值能夠在組件使用時指定 innerText: { type: String, value: 'default value', } }, data: { // 這裏是一些組件內部數據 someData: {} }, methods: { // 這裏是一個自定義方法,方法必須寫在methods內 customMethod: function(){} } })
首先要在頁面的 json
文件中進行引用聲明。還要提供對應的組件名和組件路徑xss
// 引用聲明 "usingComponents": { // 要使用的組件的名稱 // 組件的路徑 "component-tag-name": "path/to/the/custom/component" } }
組件的使用和Vue同樣,this
在wxml文件中code
<component-tag-name></component-tag-name>
父組件的wxml頁面傳輸值
<component-tag-name></component-tag-name>
子組件的wxml
<view>{{變量名}}</view>
讓父組件內顯示子組件的內容
#在組件中 properties: { 變量名:{ type:String, value:"變量值" } } //而不是把變量名放在data中
父組件頁面
頁面 <component-tag-name bind:icre="icre"></component-tag-name>
父組件的js
頁面中js icre:function(e){ console.log(e) this.setData({ num:this.data.num+1 }) },
子組件頁面
<button bindtap='clickpush'>加我</button>
子組件的js
clickpush:function(e){ console.log(e) this.triggerEvent("icre",{"index":13},{}) }