小程式自定義元件的具體實現+頁面與自定義元件間的通訊
阿新 • • 發佈:2019-01-31
具體步驟如下:
1.建立一個元件
圖中的singerList就是一個元件,元件為了規範通常放在conponents裡。
2.在頁面的json檔案裡引用元件
//想在index.wxml中引用,則對應的index.json要這樣配置
{
"usingComponents": {
"songList":"/components/songList/songList"
}
}
引用後就可以在wxml檔案裡用了
//index.wxml
...
<songList id='songList'></songlist>
...
標籤名字記得對應json檔案裡的對應的元件的key值
3.使用元件的方法和屬性
元件內定義了一個fun的方法
//songList.js
Component({
...
methods: {
fun(v){
console.log(v)
}
}
...
})
在頁面裡可以這樣呼叫
Page({
...
onready(){
this.singList = this.selectComponent("#singList");
this.singList.fun("value");
//value
}
...
})
4.頁面傳值/方法到元件
頁面裡這樣配置
//index.wxml
...
<songList
id='songList'
value1='str'
value2='{{obj}}'
bind:action:'exFun'
//exFun是你想要在元件裡呼叫的方法名
>
</songlist>
...
//index.js
Page({
data:{
obj:{
a:"one",
b:"two"
}
},
exFun(v){
console.log(v)
}
})
元件裡這樣使用
Component({
...
properties: {
//配置頁面傳過來的值,key值要一一對應
'value1':{
type:String, //必填,目前接受的型別包括:String, Number, Boolean, Object, Array, null(表示任意型別)
value:"" //可選,預設值,如果頁面沒傳值過來就會使用預設值
},
'value2':{
type:Object, //必填,目前接受的型別包括:String, Number, Boolean, Object, Array, null(表示任意型別)
value:"" //可選,預設值,如果頁面沒傳值過來就會使用預設值
}
},
methods(){
fun(){
this.triggerEvent("action");
//triggerEvent函式接受三個值:事件名稱、資料、選項值
}
}
...
})