自定義組件
從小程序基礎庫版本 1.6.3 開始,小程序支持簡潔的組件化編程。所有自定義組件相關特性都需要基礎庫版本 1.6.3 或更高。
開發者可以將頁面內的功能模塊抽象成自定義組件,以便在不同的頁面中重複使用;也可以將複雜的頁面拆分成多個低耦合的模塊,有助於代碼維護。自定義組件在使用時與基礎組件非常相似。
創建自定義組件
類似於頁面,一個自定義組件由 json wxml wxss js 4個文件組成。要編寫一個自定義組件,首先需要在 json 文件中進行自定義組件聲明(將 component 字段設爲 true 可將這一組文件設爲自定義組件):
{
"component": true
}
或者直接在components文件夾中,創建創建自定義組件文件夾my-components,然後右鍵 新建Component
編寫模板
<view>
我是組件上的內容 {{myvalue}}
</view>
使用模本
使用已註冊的自定義組件前,首先要在頁面的 json 文件中進行引用聲明。此時需要提供每個自定義組件的標籤名和對應的自定義組件文件路徑:
{
"usingComponents": {
"my-components":"/components/my-components/index"
}
}
wxml文件
<view>
<!--wxml 直接使用就好了-->
<my-components>
</my-components>
</view>
父傳子
<view>
<!--wxml 直接使用就好了 給子組件傳參 父傳-->
<my-components type="primary" myvalue="父親的值">
</my-components>
</view>
子組件index.js文件中
properties: { //接收父的參數
myvalue:{
type:"string",
value:"默認值",//這裏就結束到父 組件的值去wxml可以使用了(父傳子)
observer:(newValue,oldValue)=>{ //observer監聽 cliclkfn函數
console.log(newValue,oldValue) //輸出新值舊值
}
}
},
<view>
子使用 {{myvalue}}
</view>
點擊按鈕修改值
<view>
我是組件上的內容 {{myvalue}}
<button bindtap="cliclkfn">點擊修改值</button>
</view>
methods: {
// 點擊按鈕修改值
cliclkfn(){
// console.log('fn...')
// 修改 值
this.setData({
myvalue:"修改的值"
})
},
}
子傳父
點擊按鈕
<!-- 點擊按鈕 子組件觸發 -->
<button type="primary" bindtap="changeValue">點擊修改父級的值</button>
觸發事件
methods: {
//點擊修改父組件的值 子傳父
changeValue(){ // 參數名 參數
this.triggerEvent("myevent","參數")
}
}
父級監聽
<!-- 父組件監聽子組件-->
<my-components type="primary" myvalue="父親的值" bind:myevent="myevent">
</my-components>
獲取到數據使用
// 子組件點擊給父組件參數 父監聽,這裏輸出
myevent(e){
console.log(e.detail)
},