【问题标题】:EventBus in vue not workingVue中的EventBus不起作用
【发布时间】:2017-12-11 12:55:19
【问题描述】:

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

app.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:

import Vue from "vue";

const EventBus = new Vue();

export default EventBus;

应该触发事件的组件:

<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>

应该接收事件的组件:

<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>

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

我错过了什么?

【问题讨论】:

    标签: javascript laravel vue.js


    【解决方案1】:

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

    Vue.use(VueResource);
    
    window.EventBus = new Vue();
    
    Vue.component("map-wrapper", MapWrapper);
    

    如果使用这种方法,以后不需要导入 EventBus。 只需在任何你想要的地方使用 EventBus.$emit 和 EventBus.$!

    希望对你有帮助!

    【讨论】:

    • 照你说的做了,但同样的问题:(
    • 这是工作示例! jsfiddle.net/4do5ng92 看起来你应该像我一样在组件的 mount() 方法上添加 EventBus.$on 监听器。
    • 是的!这就是问题所在!我输入了 created() ,现在它可以工作了!谢谢!
    • 在我的例子中,我在父组件和子组件中创建了一个 EventBus 对象作为新的 Vue,而子组件没有响应。我想通过在 app.js 中创建 EventBus 一次就​​可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2017-08-02
    • 2021-06-27
    • 2022-10-17
    相关资源
    最近更新 更多