父子组件之间进行通信有 3 种办法
1、属性绑定;用于父组件向子组件的指定属性传递数据,仅能设置JSON兼容的数据。
2、事件绑定;用于子组件向父组件传递数据。
3、获取组件的实例;父组件通过this.selectComponent()获取子组件的实例对象。

属性绑定

属性绑定用于父组件向子组件传递数据,但是无法将方法传递给子组件。

  1. <view style="margin-top: 30rpx; border: 1px solid red;">
  2. <my-test2 count="{{count}}"></my-test2>
  3. </view>
  1. Component({
  2. /**
  3. * 组件的属性列表
  4. */
  5. properties: {
  6. count: String,
  7. },
  8. })
  1. <view>
  2. 这是父组件传递来的数据:{{count}}
  3. </view>

子组件事件绑定

事件绑定用于子组件向父组件传递事件。
1、子组件通过this.triggerEvent("自定义事件名称", {参数对象}),将数据发送给父组件。
2、在父组件中的wxml中通过自定义事件的形式接收子组件传递来的方法。
3、父组件在JS文件中实现这个方法,通过方法的e.detail获取子组件传递的数据。

接下来看案例:

  1. <!-- 子组件点击触发 handleTapCountAdd 方法 -->
  2. <view bind:tap="handleTapCountAdd">
  3. 这是父组件传递来的数据:{{count}}
  4. </view>
  1. Component({
  2. properties: {
  3. count: String,
  4. },
  5. methods: {
  6. handleTapCountAdd() {
  7. // 通过 this.triggerEvent 向父组件传递方法
  8. this.triggerEvent("countAdd", {
  9. number: Number(10)
  10. })
  11. }
  12. }
  13. })
  1. <view style="margin-top: 30rpx; border: 1px solid red;">
  2. <!-- 父组件通过 bind:countAdd 来接收子组件传递的方法 -->
  3. <my-test2 bind:countAdd="handleCountAdd" count="{{count}}"></my-test2>
  4. </view>
  1. Page({
  2. data: {
  3. count: 0
  4. },
  5. handleCountAdd(e) {
  6. // 通过 e.detail 来接收子组件传递来的数据
  7. const { number } = e.detail
  8. this.setData({
  9. count: number + this.data.count
  10. })
  11. }
  12. })

获取子组件实例

父组件通过this.selectCompoent("id获取class选择器"),获取子组件的实例对象,从而直接访问子组件的任意数据和方法。

  1. <view style="margin-top: 30rpx; border: 1px solid red;">
  2. <!-- 新增一个 ID -->
  3. <my-test2 id="my-test2" bind:countAdd="handleCountAdd" count="{{count}}"></my-test2>
  4. </view>
  1. Page({
  2. data: {
  3. count: 0
  4. },
  5. /**
  6. * 生命周期函数--监听页面加载
  7. */
  8. onLoad(options) {},
  9. /**
  10. * 生命周期函数--监听页面初次渲染完成
  11. */
  12. onReady() {
  13. const obj = this.selectComponent("#my-test2")
  14. console.log(obj)
  15. },
  16. })

获取到的子组件实例