赞
踩
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); // 输出:这是传递给父组件的数据
- }

以上两种方式都可以实现调用组件方法的目的,选择哪一种取决于具体情况,常规情况下建议使用第一种方式。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。