- 부모 구성 요소의 메서드를 통해 자식 구성
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); // 输出:这是传递给父组件的数据
}
위의 두 가지 방법 모두 구성 요소 메서드를 호출하는 목적을 달성할 수 있으며 특정 상황에 따라 선택할 수 있습니다.일반적으로 첫 번째 방법을 권장합니다.