通过父组件的selectComponent方法获取子组件实例,然后调用其定义的方法。例如:
// 在父组件中调用
const childComponent = this.selectComponent('#myChild');
childComponent.myMethod();
2. 直接在子组件中使用this.triggerEvent()触发一个自定义事件,父组件监听该自定义事件并执行相应的操作。例如:
Component({
methods: {
onButtonClick() {
this.triggerEvent('customEvent', { data: '这是传递给父组件的数据' });
}
}
})
// 父组件中监听自定义事件
bind:customEvent="onCustomEvent" >
onCustomEvent(event) {
console.log(event.detail.data); // 输出:这是传递给父组件的数据
}
以上两种方式都可以实现调用组件方法的目的,选择哪一种取决于具体情况,常规情况下建议使用第一种方式。
参考阅读
发表评论