使用
1.創(chuàng)建與pages同級目錄components, 用來存放組件,每個組件對應一個文件夾,文件夾內(nèi)新建Component
2.在頁面文件夾下的json文件中引入所需組件,可以自定義一些較有語義化的名字
// index.json
{
"usingComponents": {
"first": "/components/first/first",
"second": "/components/second/second"
}
}
3.在頁面內(nèi)引入使用組件
// index.wxml
<view class="box">
<first></first>
<second></second>
</view>
父子組件傳值
注意:
在 bindtap="getMsg"中, bindtap為觸發(fā)事件的方式,getMsg為 被觸發(fā)事件。
-
父傳子
- 在頁面內(nèi)的組件標簽上進行傳值,比如這里我向first組件傳遞了一個color
// index.wxml
<view class="box">
<first color="red"></first>
</view>
- 在子組件的js文件內(nèi)接收,具體在properties對象內(nèi)。type設置類型,value設置默認值
接收到值后,它會被添加到data中,我們就可以正常通過插值語法{{ }}調(diào)用它
// first.js
Component({
properties: {
color: {
type: 'string',
value: ''
}
},
})
-
子傳父
- 我們先在子組件內(nèi)定義一個方法(toFather),按鈕點擊時執(zhí)行,也是傳值的開始
// first.wxml
<view class="first">
<button bindtap="toFather">子傳父</button>
</view>
- toFather的執(zhí)行要在methods內(nèi),通過triggerEvent(官方提供的方法)自定義一個觸發(fā)事件(類似于bindtap), 并且可以傳遞一個參數(shù)(只能傳遞一項,可以是數(shù)組,對象,字符串等)
// first.js
methods: {
toFather() {
// 為父組件自定義函數(shù)
this.triggerEvent('getMsg', 110)
}
}
- 在父組件內(nèi)利用自定義的觸發(fā)事件執(zhí)行自定義方法,是在該組件標簽上執(zhí)行噢,注意自定義方法名要為: bindxxx, 如我們定義的要寫為bindgetMsg
// index.wxml
<view class="box">
<first bindgetMsg="getSonMsg"></first>
</view>
- getSonMsg定義在父組件的js文件內(nèi), 這樣就可以獲取到子組件傳來的數(shù)據(jù)了,下方代碼中的e就是我們在創(chuàng)建自定義觸發(fā)事件時傳遞的參數(shù)
Page({
data: {},
getSonMsg(e) {
console.log(e) //110
}
})
插槽
作用:如不同頁面內(nèi)的navbar結(jié)構(gòu)類似,我們就可以將相同的部分寫為固定的,不同的樣式通過插槽來修改
用法:
1.在組件js文件內(nèi),配置支持插槽
Component({
options: {
multipleSlots: true // 在組件定義時的選項中啟用多slot支持
}
})
2.在組件內(nèi)的wxml文件內(nèi),寫入插槽
// first.wxml
<slot name="head"></slot>
view
<slot name="foot"></slot>
3.在父組件內(nèi)的子組件標簽內(nèi)調(diào)用
// index.html
<first>
<view slot="head">123</view>
<view slot="foot">123</view>
</first>