laravel vue 中的 EventBus 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44967159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:16:32  来源:igfitidea点击:

EventBus in vue not working

javascriptlaravelvue.js

提问by ste

I have a Laravel (5.4) application with some Vue components in it. I would need to make some of those components communicate, so I decided to add an EventBus. The code is the following:

我有一个 Laravel (5.4) 应用程序,其中包含一些 Vue 组件。我需要让其中一些组件进行通信,因此我决定添加一个 EventBus。代码如下:

app.js:

应用程序.js:

import VueResource from "vue-resource";
import Vue from "vue";
import Menu from "components/src/core/Menu.vue";

import MapWrapper from "./components/MapWrapper.vue";
import PaymentModal from "./components/PaymentModal.vue";

require("../sass/app.scss");

Vue.use(VueResource);

Vue.component("map-wrapper", MapWrapper);
Vue.component("my-menu", Menu);
Vue.component("payment-modal", PaymentModal);

// eslint-disable-next-line
new Vue({
    el: "#app",
});

event.js:

事件.js:

import Vue from "vue";

const EventBus = new Vue();

export default EventBus;

component that should trigger the event:

应该触发事件的组件:

<template>
    <div style="height: 100%; width: 100%;">
        <button @click="emitEvent">Click me</button>
    </div>
</template>

<script>
import Vue from "vue";    
import EventBus from "../event";

export default {
    methods: {
        emitEvent() {
            console.log(EventBus);
            EventBus.$emit("testEvent", "test");
        },
    },
};
</script>
<style>
</style>

component that should receive the event:

应该接收事件的组件:

<template>
    <div>
    </div>
</template>

<script>
import EventBus from "../event";

export default {
    computed: {
        test() {
            EventBus.$on("testEvent", ($event) => {
                console.log("event triggered", $event);
            });
        },
    },
};
</script>

<style>
</style>

The problem is that when I click the button I can see the EventBus logged by the console, but nothing else happen, the receiving components does not catch the event.

问题是,当我单击按钮时,我可以看到控制台记录的 EventBus,但没有其他任何事情发生,接收组件没有捕获事件。

What am I missing?

我错过了什么?

回答by Emīls Gulbis

You should create EventBus on app.js before defining Vue components.

在定义 Vue 组件之前,您应该在 app.js 上创建 EventBus。

Vue.use(VueResource);

window.EventBus = new Vue();

Vue.component("map-wrapper", MapWrapper);

Isn't necessary to import EventBus later if using this approach. Just use EventBus.$emit and EventBus.$on everywhere you want!

如果使用此方法,则无需稍后导入 EventBus。只需在任何地方使用 EventBus.$emit 和 EventBus.$on 即可!

Hope it helps!

希望能帮助到你!