一:定義組件
在miniprogram
下的目錄下創(chuàng)建一個components
文件夾,與pages
目錄同級,這個文件夾專門是用來放自定義組件的
例如:在components
目錄下創(chuàng)建了一個count
文件夾,然后在新建Component
,組件名稱命名為count
,微信開發(fā)者工具會自動的創(chuàng)建count
組件
// =============count.wxml==================
<view>
<view class="count-container">
<view bindtap="reduce" class="{{count == 1? 'btn-disabled': ''}}}">-</view>
<input bindinput="handleInput" type="number" value="http://www.wxapp-union.com/{{count}}" />
<view bindtap="add">+</view>
</view>
</view>
// =============count.js================
// components/count/count.js
Component({
/**
* 組件的屬性列表
*/
properties: {
count: Number,
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {},
/**
* 組件的方法列表
*/
methods: {
reduce() {
var count = this.data.count - 1;
if (count < 1) {
count = 1;
}
this.setData({
count,
});
this.triggerEvent('changeCount', count);
console.log(this.data.count);
},
add() {
var count = this.data.count + 1;
this.setData({
count,
});
this.triggerEvent('changeCount', count);
console.log(this.data.count);
},
handleInput(event) {
this.setData({
count: event.detail.value,
});
this.triggerEvent('changeCount', event.detail.value); // 向外暴露函數(shù)
},
},
});
復(fù)制代碼
二:使用組件
在pages
目錄下,這里我創(chuàng)建了一個customComponents
頁面
在要使用頁面對應(yīng)的customComponents.json
中的usingComponents
自定義組件的名稱,同時引入組件的路徑
// customComponents.json
{
"usingComponents": {
"count":"/components/count/count"
}
}
復(fù)制代碼
// customComponents.wxml
<count count="{{countNum}}" bind:changeCount="handleCount"></count>
<view class="parentText">父組件count:{{countNum}}</view>
復(fù)制代碼
****// pages/customComponents/customComponents.js
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
countNum: 1,
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad: function(options) {},
// 父組件中自定義綁定的事件
handleCount(event) {
this.setData({
countNum: event.detail, // 獲取子組件傳遞過來的值
});
},
});
復(fù)制代碼
三:小程序中組件的通信與事件
-
父傳子
wxml
數(shù)據(jù)綁定:用于父組件向子組件指定屬性設(shè)置數(shù)據(jù),在子組件中properties
對象接收外部(父)組件傳過來的自定義屬性數(shù)據(jù),可以是對象,數(shù)組,基本數(shù)據(jù)類型等。
注釋:
properties
類似于vue
中的props
,react
中的this.props
-
子傳父
- 事件: 用于子組件通過
this.triggerEvent()
向父組件傳遞數(shù)據(jù),可以傳遞任意數(shù)據(jù),父組件通過綁定綁定監(jiān)聽事件,從而觸發(fā)父組件自定義事件,event.detail
是子組件傳遞過來的值。
注意:
triggerEvent
,就相當(dāng)于vue
中的this.$emit('綁定在父組件自定義事件名稱',攜帶的數(shù)據(jù))
方法的,而在React
中是通過this.props
.方法接收,調(diào)用父組件的方法。 - 事件: 用于子組件通過
-
在父組件中還可以通過
this.selectComponent("類名或ID")
方法獲取子組件的實(shí)例對象,這樣在父組件中不必通過event.detail
的方式獲取,可以直接訪問子組件任意的數(shù)據(jù)和方法。
前提條件:
需要在父組件的引用自定義組件上,添加class
或id
<count
class="count"
count="{{countNum}}"
bind:changeCount="handleCount"
></count>
復(fù)制代碼
那么,在父組件中的handleCount
中里調(diào)用 this.selectComponent
,獲取子組件的實(shí)例數(shù)據(jù)
調(diào)用時需要傳入一個匹配選擇器 class
與Id
都可以,如,this.selectComponent('類或ID')
handleCount(){
var count = this.selectComponent('.count'); // 獲取子組件的實(shí)例
this.setData({
countNum: count.data.count // 重新賦值setData countNum數(shù)據(jù)
})
}
復(fù)制代碼