微信小程序调用子组件的方法

  1. 通过父组件的selectComponent方法获取子组件实例,然后调用其定义的方法。例如:
<!-- 父组件 -->
<view>
  <child-component id="myChild" />
</view>

// 在父组件中调用
const childComponent = this.selectComponent('#myChild');
childComponent.myMethod();

   2. 直接在子组件中使用this.triggerEvent()触发一个自定义事件,父组件监听该自定义事件并执行相应的操作。例如:

<!-- 子组件 -->
<view>
  <button bindtap="onButtonClick">点击按钮</button>
</view>

Component({
  methods: {
    onButtonClick() {
      this.triggerEvent('customEvent', { data: '这是传递给父组件的数据' });
    }
  }
})

// 父组件中监听自定义事件
<child-component 
  bind:customEvent="onCustomEvent"
></child-component>

onCustomEvent(event) {
  console.log(event.detail.data); // 输出:这是传递给父组件的数据
}

以上两种方式都可以实现调用组件方法的目的,选择哪一种取决于具体情况,常规情况下建议使用第一种方式。

猜你喜欢

转载自blog.csdn.net/qq_53478650/article/details/129796569