有没有办法从VueJS中的父级触发组件方法?

新手上路,请多包涵

我一直在搜索信息,并且只找到了一种从子组件发出事件的方法,然后可以在父组件中监听这些事件。有没有办法从父组件调用子方法?

原文由 naneri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 524
2 个回答

是的,只需在 children 数组中找到您的组件,或者通过 ref 属性获取它,然后调用方法 :) ref doc

假设您的子组件具有方法 x。根据文档:

 <div id="parent">
  <user-profile ref="profile"></user-profile>
</div>

var child = this.$refs.profile;
child.x();

原文由 donMateo 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为一个好的模式是从父组件发出一个事件并在子组件中使用 Event Bus 监听它。

那将是:

在 main.js 中

export const bus = new Vue()

在 Parent.vue 中:

 import {bus} from 'path/to/main'

// Where you wanna call the child's method:
bus.$emit('customEventName', optionalParameter)

在 Child.vue 中:

 import {bus} from 'path/to/main'

// Add this to the mounted() method in your component options object:
bus.$on('customEventName', this.methodYouWannaCall)

原文由 bformet 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题