简体   繁体   English

从父(App.vue)到另一个组件的Vue事件

[英]Vue Event from Parent (App.vue) To Another Component

I would like to emit an event from App.vue which is a main component to another component. 我想从App.vue发出一个事件,它是另一个组件的主要组件。 EventBus.$emit from App.vue, EventBus.$on on child/another component is not working. EventBus.$emit从App.vue EventBus.$emitEventBus.$on on child / EventBus.$on组件无法正常工作。 Since there is no child relation directly between these, I cannot use @custom-event="" either 由于这些之间没有直接的子关系,我也不能使用@custom-event=""

How can I throw an event from App.vue to another component? 如何将App.vue的事件App.vue到另一个组件?

That's what I do. 我就是做这个的。 It is working all of the other components. 它正在处理所有其他组件。 Here my components' folder structure 这是我的组件的文件夹结构

-src
-pages
  -main-page
    -MainPage.vue  $on
-event
-constant
-store
-router
App.vue  --> $emit
main.js

You say the EventBus method isn't working but it should be so I'll assume you're doing it wrong. 你说EventBus方法不起作用,但它应该是这样我会假设你做错了。 Do something like this: 做这样的事情:

Create eventBus.js 创建eventBus.js

import Vue from 'vue';
export const EventBus = new Vue();

In any of your single file components, import it: 在任何单个文件组件中,导入它:

import { EventBus } from '/src/path/to/eventBus.js';

Trigger an event in a component: 触发组件中的事件:

EventBus.$emit('some-event-raised', { someData: "bob" })

In any other component, do the import again and then listen: 在任何其他组件中,再次执行导入然后监听:

EventBus.$on('some-event-raised', obj => {
  console.log(`some-event-raised triggered [${obj.someData}]`)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM