小程序组件间的通信方式(三种)

1,046 阅读1分钟

小程序组件间的通信方式(三种)

1,属性绑定(父向子传值)

  • 用于父组件向子组件的的指定属性设置数据,仅能设置 JSON 兼容的数据
  • 只能传递普通类型的数据,无法将方法传递给子组件

父组件

<my_text count="{{count}}"></my_text>
data: {
  count: 10
}

子组件

// 组件使用 properties 去接收
properties: {
  count: Number
}
<!-- 子组件使用 -->
子组件中:count--{{count}}

2,事件绑定

  • 用于子组件向父组件传递数据,可以传递任意数据

父组件

sync:事件名称,可以自定义
<my_text count="{{count}}" bind:sync="syncCount"></my_text>

子组件

<button bindtao="countAdd">count+1</count>
countAdd(){
 this.setData({
   count: this.properties.count+1
 })
 
 this.triggerEvent('sync', {value: this.properties.count})
}

3,获取组件实例

  • 父组件通过this.selectComponent() 获取子组件实例对象
  • 这样可以直接访问子组件的任意数据和方法

父组件

<my_text count="{{count}}" bind:sync="syncCount" class="countClass"></my_text>

<button bindtab="getChild">获取子组件的实例</button>
getChild(){
  let childData = this.selectAllComponents('.countClass')[0]
  // 调用子组件中的属性
  this.setData({
    count: childData.properties.count+1
  })
  
  // 调用子组件中的方法
  childData.countAdd()
}