1、在根目錄新建components文件夾,並在裏面添加組件
二、組件的配置
1,json文件
{
"component": true
}
2,wxml文件
<view >我是子組件</view>
<button bindtap="btnclick">按鈕</button>
3,wxss文件( 需要導入全局樣式 )
@import '../../app.wxss'
三、導入自定義組件
1,在父組件json文件的usingComponents中導入組件
{
"usingComponents": {
"test":"/components/submit/index"
}
}
2,在父組件wxml文件中以組件名作爲標籤使用組件
<test></test>
到此爲止即可看到子組件顯示內容!
四、組件的通信
1、父傳子
(1)在父組件中的子組件標籤添加屬性
<test totalMoney="{{totalMoney}}" ></test>
(2)子組件在js中通過properties接收即可
Component({
properties: {
totalMoney: Number
}
})
2、子傳父
(1)在父組件的子組件標籤自定義事件,傳給子組件
<test bind:submit="submit" ></test>
submit(event) {
console.log(event);
},
(2)子組件用this.triggerEvent('父組件自定義事件', '要傳遞的參數')
,觸發父組件傳過來的自定義事件
Component({
properties: {
totalMoney: Number
},
methods:{
//子組件事件
btnclick(){
console.log('aaaaaaaaaaaaaaaaaaa');
this.triggerEvent("submit", 'Hello lily')
}
}
})
(3)第二步執行後,父組件自定義事件綁定的函數就會執行,同時接受子組件傳過來的數據
(在event.detail中可得到子組件傳過來的參數)