微信小程序-Component(組件)

1.創(chuàng)建組件

打開微信開發(fā)者工具,創(chuàng)建組件,會生成四個文件:wxml,wxss,js,json

在wxml中:

我是組件A

在js中:

Component({? behaviors: [],? properties: {? ? },? data: {? ? },// 私有數(shù)據(jù),可用于模版渲染// 生命周期函數(shù),可以為函數(shù),或一個在methods段中定義的方法名attached:function(){ },? moved:function(){ },? detached:function(){ },? methods: {? ? }})

在json中:

{"component":true,"usingComponents": {}}

即組件創(chuàng)建完成

2.引入組件

要在index中引入組件,則

在index.json中:

{"usingComponents": {"componentA":"../../components/child1/child1"}}

在index.wxml中:

微信小程序組件傳參

則組件就能夠顯示,要使得組件引入,先要在json中去給組件定義一下才可在wxml中顯示

3.父組件向子組件傳參

聲明: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ù),或一個在methods段中定義的方法名attached:function(){ },moved:function(){ },detached:function(){ },methods: {? }})

即在properties中定義A組件要傳過來的參數(shù)類型

在B組件的wxml中寫入:

我是組件BA中傳入的參數(shù):{{paramAtoB}}

總結(jié):?A組件向B組件傳參,實(shí)際上就是在A組件中引入B組件的時候,帶上一個屬性paramAtoB,并且給其賦值,然后B組件通過這個屬性名稱paramAtoB,獲取其值

4.子組件向父組件傳參

聲明:A組件為父組件,B組件為子組件,以下是B組件向A組件傳參:

要讓子組件給父組件傳參,首先得在父組件引入子組件的時候,加個觸發(fā)事件,如下:

在父組件A中wxml:

我是組件AA組件內(nèi)容:B組件傳入?yún)?shù):{{paramBtoA}}

myevent就是綁定的觸發(fā)事件

在父組件A中js:

Component({? behaviors: [],? properties: {? ? },? data: {? },// 私有數(shù)據(jù),可用于模版渲染// 生命周期函數(shù),可以為函數(shù),或一個在methods段中定義的方法名attached:function(){ },? moved:function(){ },? detached:function(){ },? methods: {? ? onMyEvent:function(e){this.setData({? ? ? ? paramBtoA: e.detail.paramBtoA? ? ? })? ? }? }})

onMyEvent就是當(dāng)被子組件觸發(fā)時的函數(shù)

在子組件B中wxml:

我是組件BA中傳入的參數(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ù),或一個在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)入父組件

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容