我一直在搜索信息,并且只找到了一种从子组件发出事件的方法,然后可以在父组件中监听它们.有没有办法从父组件调用子方法?
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)
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)
| 归档时间: |
|
| 查看次数: |
23677 次 |
| 最近记录: |