Suc*_*Man 1 vue.js vue-component vuex vuejs2 vuex-modules
我有 4 个组件
我的组件首先是这样的:
<template>
...
<component-second></component-second>
...
</template>
<script>
...
export default {
...
updated() {
// call check method in the component fourth
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
我的第二个组件是这样的:
<template>
...
<component-third></component-third>
...
</template>
<script>
...
export default {
...
}
</script>
Run Code Online (Sandbox Code Playgroud)
我的第三个组件是这样的:
<template>
...
<component-fourth></component-fourth>
...
</template>
<script>
...
export default {
...
}
</script>
Run Code Online (Sandbox Code Playgroud)
我的第四个组件是这样的:
<template>
...
</template>
<script>
...
export default {
...
methods: {
check() {
...
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
因此,如果首先执行组件中的 update(),我想在第四个组件中调用 check 方法
我该怎么做?
您可以使用 Vue 实例作为事件总线。
您将创建一个全局变量:
var eventHub = new Vue(); // use a Vue instance as event hub
Run Code Online (Sandbox Code Playgroud)
要发出您将在任何组件中使用的事件:
eventHub.$emit('myevent', 'some value');
Run Code Online (Sandbox Code Playgroud)
并且,要再次在任何组件中收听该事件,请执行以下操作:
eventHub.$on('myevent', (e) => {
console.log('myevent received', e)
});
Run Code Online (Sandbox Code Playgroud)
演示:
var eventHub = new Vue(); // use a Vue instance as event hub
Run Code Online (Sandbox Code Playgroud)
eventHub.$emit('myevent', 'some value');
Run Code Online (Sandbox Code Playgroud)
注意:如果在您的环境中创建专用实例作为事件中心是一件很复杂的事情,您可以替换eventHub为this.$root(在您的组件中)并使用您自己的 Vue 实例作为中心。
| 归档时间: |
|
| 查看次数: |
2749 次 |
| 最近记录: |