- 親コンポーネントのメソッドを通じて子コンポーネントのインスタンスを取得し
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); // 输出:这是传递给父组件的数据
}
上記 2 つの方法はどちらもコンポーネント メソッドを呼び出すという目的を達成できますが、どちらを選択するかは特定の状況によって異なり、通常は最初の方法が推奨されます。