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組件傳參癞尚,實際上就是在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按鈕點擊事件一觸發(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就是按鈕點擊之后執(zhí)行的事件,觸發(fā)myevent事件窜护,傳入?yún)?shù)paramBtoA進(jìn)入父組件