【发布时间】:2017-09-15 13:56:53
【问题描述】:
我一直在搜索信息,并且只找到了一种从子组件发出事件的方法,然后可以在父组件中监听这些事件。有没有办法从父组件调用子方法?
【问题讨论】:
标签: vue.js
我一直在搜索信息,并且只找到了一种从子组件发出事件的方法,然后可以在父组件中监听这些事件。有没有办法从父组件调用子方法?
【问题讨论】:
标签: vue.js
是的,只需在 children 数组中找到您的组件,或者通过 ref 属性获取它,然后调用方法 :) ref doc
假设您的子组件具有方法 x。 根据文档:
<div id="parent">
<user-profile ref="profile"></user-profile>
</div>
var child = this.$refs.profile;
child.x();
【讨论】:
我认为一个很好的模式是从父组件发出一个事件并在子组件中使用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)
【讨论】:
<component ref="componentRef"> ... this.$refs.componentRef.theMethod()
这是一个简单的
this.$children[indexOfComponent].childsMethodName();
【讨论】: