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

nan*_*eri 36 vue.js

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

don*_*teo 76

是的,只是在子数组中找到你的组件,或者通过ref属性获取它,并调用方法:) ref doc

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

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

var child = this.$refs.profile;
child.x();
Run Code Online (Sandbox Code Playgroud)

  • "无法读取未定义的属性"个人资料" (5认同)
  • 这是一种不好的做法,因为它会破坏推荐数据和组件中的事件流。 (3认同)
  • 此处相同“无法读取未定义的属性“配置文件””。ref 属性适用于本机元素,但不适用于自定义组件。 (2认同)
  • 但是,如果您使用第三方组件并且没有任何公开的 API 该怎么办?这可能是不好的做法,但有时你别无选择...... (2认同)

bfo*_*met 14

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

那将是:

在main.js

export const bus = new Vue()
Run Code Online (Sandbox Code Playgroud)

在Parent.vue中:

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

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

在Child.vue中:

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

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

  • @tatsu它创建一个额外的Vue实例,并使用Vue实例提供的方法来实现事件总线. (4认同)
  • 只需将 ref 属性传递给组件并使用它来调用其方法 `&lt;component ref="componentRef"&gt; ... this.$refs.componentRef.theMethod()` (2认同)