当前位置:   article > 正文

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

微信小程序父组件调用子组件方法
  1. 通过父组件的selectComponent方法获取子组件实例,然后调用其定义的方法。例如:
  1. <!-- 父组件 -->
  2. <view>
  3. <child-component id="myChild" />
  4. </view>
  5. // 在父组件中调用
  6. const childComponent = this.selectComponent('#myChild');
  7. childComponent.myMethod();

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

  1. <!-- 子组件 -->
  2. <view>
  3. <button bindtap="onButtonClick">点击按钮</button>
  4. </view>
  5. Component({
  6. methods: {
  7. onButtonClick() {
  8. this.triggerEvent('customEvent', { data: '这是传递给父组件的数据' });
  9. }
  10. }
  11. })
  12. // 父组件中监听自定义事件
  13. <child-component
  14. bind:customEvent="onCustomEvent"
  15. ></child-component>
  16. onCustomEvent(event) {
  17. console.log(event.detail.data); // 输出:这是传递给父组件的数据
  18. }

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/382051
推荐阅读
相关标签
  

闽ICP备14008679号