微信小程序中的组件传值

    科技2022-08-09  96

    父传子

    父组件中的json文件

    { "component": true, //设置component为true "usingComponents": { "componentB": "../child2/child2" //这个是引入子组件 } }

    第二步是在父组件中的wxml中使用子组件中模块

    <view> //这个是父组件的内容 <view>子组件内容:</view> <componentB customAttribute='我是A向B中传入的参数'/> //这里customAttribute是自定义属性 </view>

    在子组件中:

    Component({ behaviors: [], properties: { paramAtoB:String //声明父组件传过来的类型为string类型 }, data: { }, // 这里放的是子组件的私有数据,可用于模版渲染 // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 attached: function () { }, moved: function () { }, detached: function () { }, methods: { } })

    在父组件中使用:

    <view>父组件中传来的参数:{{customAttribute}}</view>

    子传父

    子组件中的wxml:

    <view> <button bindtap='customEvent'>A中传入参数</button> //customEvent事件名--点击触发 </view> 12345

    子组件中的js

    Component({ behaviors: [], properties: { }, data: { }, attached: function () { }, moved: function () { }, detached: function () { }, methods: { change:function(){ this.triggerEvent('myevent', { msg:123}); //这里的this.triggerEvent相当于一个发射器 发射一个事件给父组件 //(myevent)第一个参数是自定义事件,{msg:123}第二个参数是要传递的数据 } } })

    父组件中接受参数:

    <componentB paramAtoB='我是A向B中传入的参数' bind:myevent="onMyEvent"/> //在父组件的子模板上绑上子模板传过来的事件 (myevent) //子组件点击事件后传到父组件,父组件所处理数据的事件onMyEvent 123

    事件执行,通过e.detail.msg获取到子传递过来的数据

    Component({ behaviors: [], properties: { }, data: { }, // 私有数据,可用于模版渲染 // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 attached: function () { }, moved: function () { }, detached: function () { }, methods: { onMyEvent:function(e){ console.log(e.detail.msg) \\e.detail.paramBtoA这就是子传父传递过来的数据 } } })
    Processed: 0.015, SQL: 8