微信小程序父级之间的传值_微信小程序自定义组件封装及父子间组件传值的方法...
首先在我們可以直接寫到需要的 page 中,然后再進(jìn)行抽取組件,自定義組件建議wxzx-xxx命名
例如,我們封裝的組件名為 **wxzx-loadmore
wxzx-loadmore.wxml
正在加載
{{tip}}
這里就是把index.wxml中的需要封裝成組件的代碼原樣copy過來
wxzx-loadmore.js
Component({
/**
* 組件的屬性列表
*/
properties: {
response: {
type: String,
value: ''
},
is_loadmore: {
type: Boolean,
value: false
},
tip: {
type: String,
value: '我是有底線的'
}
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
},
/**
* 組件的方法列表
*/
methods: {
emit: function(data) {
// 自定義組件向父組件傳值
let val = data,
my_event_detail = {
val: val
}
// myevent自定義名稱事件,父組件中使用
this.triggerEvent('myevent', my_event_detail)
/*
在父組件中寫上bind:myevent="get_emit",在父組件中就需要調(diào)用get_emit事件
*/
},
}
})
index.wxml 父組件
response="{{comment_list}}"
is_loadmore="{{is_loadmore}}"
bind:myevent="get_emit"
>
index.js 中
// 接受子組件的傳值
get_emit: function(e) {
this.setData({
is_show: e.detail.val
})
},
index.json 這里需要引入組件,在哪個(gè)父頁面中引用子組件,就在哪個(gè)json文件中引入
{
"usingComponents": {
"wxzx-loadmore": "/component/wxzx-loadmore/wxzx-loadmore"
}
}
父組件向子組件傳參
聲明:A組件為父組件,B組件為子組件,以下是A組件向B組件傳參:
在A組件中引入B組件
在A組件的json中寫入:
{
"component": true,
"usingComponents": {
"componentB": "../child2/child2"
}
}
在A組件的wxml中寫入:
我是組件A
子組件內(nèi)容:
在B組件的js中寫入:
Component({
behaviors: [],
properties: {
paramAtoB:String
},
data: {
}, // 私有數(shù)據(jù),可用于模版渲染
// 生命周期函數(shù),可以為函數(shù),或一個(gè)在methods段中定義的方法名
attached: function() { },
moved: function() { },
detached: function() { },
methods: {
}
})
即在properties中定義A組件要傳過來的參數(shù)類型
在B組件的wxml中寫入:
我是組件B
A中傳入的參數(shù):{{paramAtoB}}
總結(jié): A組件向B組件傳參,實(shí)際上就是在A組件中引入B組件的時(shí)候,帶上一個(gè)屬性paramAtoB,并且給其賦值,然后B組件通過這個(gè)屬性名稱paramAtoB,獲取其值
子組件向父組件傳參
聲明:A組件為父組件,B組件為子組件,以下是B組件向A組件傳參:
要讓子組件給父組件傳參,首先得在父組件引入子組件的時(shí)候,加個(gè)觸發(fā)事件,如下:
在父組件A中wxml:
我是組件A
A組件內(nèi)容:
B組件傳入?yún)?shù):{{paramBtoA}}
myevent就是綁定的觸發(fā)事件
在父組件A中js:
Component({
behaviors: [],
properties: {
},
data: {
}, // 私有數(shù)據(jù),可用于模版渲染
// 生命周期函數(shù),可以為函數(shù),或一個(gè)在methods段中定義的方法名
attached: function() { },
moved: function() { },
detached: function() { },
methods: {
onMyEvent:function(e){
this.setData({
paramBtoA: e.detail.paramBtoA
})
}
}
})
onMyEvent就是當(dāng)被子組件觸發(fā)時(shí)的函數(shù)
在子組件B中wxml:
我是組件B
A中傳入的參數(shù):{{paramAtoB}}
向A中傳入?yún)?shù)
button按鈕點(diǎn)擊事件一觸發(fā),就可以傳入?yún)?shù)進(jìn)入父組件A中,在子組件B中js:
Component({
behaviors: [],
properties: {
paramAtoB:String
},
data: {
}, // 私有數(shù)據(jù),可用于模版渲染
// 生命周期函數(shù),可以為函數(shù),或一個(gè)在methods段中定義的方法名
attached: function() { },
moved: function() { },
detached: function() { },
methods: {
change:function(){
this.triggerEvent('myevent', { paramBtoA:123});
}
}
})
this.triggerEvent就是按鈕點(diǎn)擊之后執(zhí)行的事件,觸發(fā)myevent事件,傳入?yún)?shù)paramBtoA進(jìn)入父組件
總結(jié)
以上是生活随笔為你收集整理的微信小程序父级之间的传值_微信小程序自定义组件封装及父子间组件传值的方法...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 响应式网站怎么设置(响应式网站怎么设置密
- 下一篇: alertmanager 告警恢复_Pr