自定义组件⑧父子组件之间的通信-微信小程序开发(二十五)

1. 父子组件之间通信的 3 种方式

① 属性绑定
⚫ 用于父组件向子组件的指定属性设置数据,仅能设置 JSON 兼容的数据
② 事件绑定
⚫ 用于子组件向父组件传递数据,可以传递任意数据
③ 获取组件实例
⚫ 父组件还可以通过 this.selectComponent() 获取子组件实例对象
⚫ 这样就可以直接访问子组件的任意数据和方法

2. 属性绑定

属性绑定用于实现父向子传值,而且只能传递普通类型的数据,无法将方法传递给子组件。父组件的示例代码如下:

//父组件的data节点
data: {
    count:0,
  }

<!-- 父组件的wxml结构 -->
<my-test count="{{count}}"></my-test>
<view>父组件中,count的值为:{{count}}</view>

子组件在 properties 节点中声明对应的属性并使用。示例代码如下:

//子组件 .js文件中的properties 节点
Component({
  properties: {
    count:Number
  }
})
//子组件的wxml结构
<text>子组件中,count值为:{{count}}</text>

注意:如果子组件的属性是驼峰命名的,如 imgList,那么调用子组件绑定属性的时候要使用横杠分开,因为不支持驼峰。

//父组件
<my-test img-list="{{imgList}}"></my-test>

//子组件 .js文件中的properties 节点
Component({
  properties: {
    imgList:Array
  }
})

3. 事件绑定

事件绑定用于实现子向父传值,可以传递任何类型的数据。使用步骤如下:
① 在父组件的 js 中,定义一个函数,这个函数即将通过自定义事件的形式,传递给子组件
② 在父组件的 wxml 中,通过自定义事件的形式,将步骤 1 中定义的函数引用,传递给子组件
③ 在子组件的 js 中,通过调用 this.triggerEvent('自定义事件名称', { /* 参数对象 */ }) ,将数据发送到父组件
④ 在父组件的 js 中,通过 e.detail 获取到子组件传递过来的数据
步骤1:在父组件的 js 中,定义一个函数,这个函数即将通过自定义事件的形式,传递给子组件。

  methods: {
    //在父组件中定义 syncCount 方法
    //将来,这个方法会被传递给子组件,供子组件进行调用
    syncCount(){
      console.log('syncCount')
    }
}

步骤2:在父组件的 wxml 中,通过自定义事件的形式,将步骤 1 中定义的函数引用,传递给子组件。

<!-- 使用 bind:自定义事件名称(推荐此写法:结构清晰) -->
<my-test count="{{count}}" bind:sync="syncCount"></my-test>
<!-- 或在 bind 后面直接写上自定义事件名称 -->
<my-test count="{{count}}" bindsync="syncCount"></my-test>

步骤3:在子组件的 js 中,通过调用 this.triggerEvent(‘自定义事件名称’, { /* 参数对象 */ }) ,将数据发送到父组件。

//子组件的wxml结构
<text>子组件中,count的值为:{{count}}</text>
<button type="primary" bindtap="addCount"> +1 </button>

//子组件的 js代码
  methods: {
    addCount(){
      this.setData({
        count:this.properties.count + 1
      })
      this.triggerEvent('sync',{value:this.properties.count})
    }
}

步骤4:在父组件的 js 中,通过 e.detail 获取到子组件传递过来的数据。

    syncCount(e){
      this.setData({
        count:e.detail.value
      })
    }

4. 获取组件实例

可在父组件里调用 this.selectComponent("id或class选择器") ,获取子组件的实例对象,从而直接访问子组件的任意数据和方法。
调用时需要传入一个选择器,例如 this.selectComponent(".my-component")。

//wxml 结构
<my-test count="{{count}}" bind:sync="syncCount" class="customA" id="cA"></my-test>
<button bindtap="getChild">获取子组件的实例</button>

//js文件
getChild(){ //按钮的tap事件处理函数
  //切记下面参数不能传递标签选择器 'my-test' ,不然返回的是 null
  const child = this.selectComponent('.customA') //或者也可以使用id选择器 #cA
  child.setData({count:child.properties.count + 1}) //调用子组件的 setData 方法
  child.addCount() // 调用子组件的addCount 方法
}
posted @ 2022-08-13 14:55  清和时光  阅读(235)  评论(0编辑  收藏  举报