參照這里
這里將重要的點貼一下:
一、項目目錄結構
在項目同級目錄新建components文件夾,新建component會生成wxml,wxss,js,json文件。將所有的公共組件都寫在此文件夾下。
二、組件引入和使用
我們的所有頁面一般寫在pages目錄下,每個頁面有wxml,wxss,js,json四個文件,在需要使用組件的頁面.json文件中,引入
{
"usingComponents": {
"componentA": "../../components/child1/child1"
}
}
在.wxml中使用
<view>
<view>微信小程序組件傳參</view>
<componentA />
</view>
三、子組件觸發父組件事件
父組件.wxml:
<component bind:myevent="onMyEvent"/>
使用bind:自定義觸發事件
父組件.js
onMyEvent:function(e){
// 事件處理,比如對data賦值操作
}
子組件.js
this.triggerEvent('myevent') // 觸發父組件方法
若要傳值:
子組件.js
this.triggerEvent('myevent', {key: value}) // 傳值
父組件:
onMyEvent:function(e){
e.detail.key // 獲取到傳過來的值
}
四、父組件向子組件傳值
父組件.wxml
<component key="{{value}}"/>
data: {
value: '1111'
}
key為子組件中 properties自定義的值,value為父組件中data定義的值
子組件.js
properties: {
key: {
type: String
}
},
子組件.wxml
<view>{{key}}</view>