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

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

47094 次浏览

是的,只要在子数组中找到您的组件,或者通过 ref 属性获取它,然后调用 method:) 裁判官

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

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


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

我认为一个好的模式是从父组件发出一个事件并在子组件中监听它,使用 活动巴士

那就是:

在 Main Js

export const bus = new 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)

这是一个简单的问题

this.$children[indexOfComponent].childsMethodName();