在小程序的实际开发中,经常会遇到父子间组件的传参问题,父组件里边的内容需要传给组件,以用来渲染页面。所以接下来就围绕父子之间如何传参,给大家演示一下实例。
首先创建组件father和组件son,定义father组件为父组件,son组件为子组件。
父组件向子组件传参
<!--pages/father/father.wxml-->
<view>我是组件A</view>
<view>
<componentB paramAtoB="{{arr}}"></componentB>
</view>
//arr是在组件father中data的数据,将它传给子组件son,paramAtoB是在子组件中定义传过来的数据的类型
在father.json中引入组件
{
"usingComponents": {
"componentB":"../son/son"
}
}
father.js
data: {
arr:[1,2,3,4,5,6]
},
son.wxml
<view>我是组件B</view>
<view>以下是父组件A传给我的</view>
<view style="color:#0fa">{{paramAtoB}}</view>
son.js
properties: {
paramAtoB: Array
},
//子组件即在**properties**中定义father组件要传过来的参数类型
传参成功的效果
子组件向父组件传参
注意:这里我是让子组件给当前调用它的页面传参,和父子组件之间传参稍微有所不同。
要让子组件给父组件传参,需要在父组件引入子组件的时候,加个触发事件
father.wxml
监听的函数myevent就是在子组件中定义的点击触发函数(change)里边的自定义事件。
onMyevent函数就是被子组件触发的时候的函数,获取子组件传来的值
<!--pages/father/father.wxml-->
<view>我是组件A</view>
<view>来自son的参数</view>
<view style="color:red">{{paramBtoA}}</view>
<view>
<componentB paramAtoB="{{arr}}" bind:myevent="onMyevent"></componentB>
</view>
father.js
onMyevent: function(e) {
this.setData({
paramBtoA: e.detail.paramBtoA
})
},
son.wxml
绑定一个点击事件,触发之后就可以将参数带入父组件
<view>我是组件B</view>
<view>以下是父组件A传给我的</view>
<view style="color:#0fa"> {{paramAtoB}}</view>
<button bindtap="change">向father传入参数</button>
son.js
methods: {
change: function() {
this.triggerEvent('myevent',{paramBtoA:1798})
}
}
成功效果
最后总结一下,当父组件给子组件传参的时候,用的其实就是properties,在子组件中定义父组件传过来的值类型。
当子组件给父组件传参的时候,需要一个触发事件,在子组件中定义一个点击事件,当点击事件触发的时候,产生一个自定义事件,用triggerEvent方法定义,并且携带参数,在父组件中监听这个自定义参数,获取其中的数据,从而实现子组件向父组件传值