【问题标题】:Why Vue global EventBus do not work in my project为什么 Vue 全局 EventBus 在我的项目中不起作用
【发布时间】:2019-10-15 09:06:32
【问题描述】:

我在 laravel 中使用 vue js,需要使用全局事件总线。我创建了 event-bus.js,并将它导入到我需要使用的地方;当我单击时,会生成事件,但听众没有反应。我尝试了一切,但它不起作用。请帮帮我,我已经工作了3天了

我尝试在 app.js 中创建一个 eventBus,但也没有用

我的 EditDiscountComponent

import { EventBus } from "../../../event-bus";

editDiscount () {
        const data = {
          discount_id: this.discountData.discount_id,
          status: this.discountData.status,
          type: this.discountData.type,
          percentage:this.discountData.percentage,
          amount:this.discountData.amount,
        };

        EventBus.$emit('update-discount', data);

         this.languages.forEach(lang => {
              if (lang.code && this.discountData[lang.code] !== undefined) {
                  data[lang.code] = this.discountData[lang.code];
              }
          });
        this.$store.dispatch(actions.EDIT_DISCOUNT, data)
          .then(res => {
            if (res && res.data.status) {

              // window.location.href = '/admin/discounts';

            } else {
              this.$store.commit(mutations.SET_SNACKBAR_SHOW, true);
              this.$store.commit(mutations.SET_SNACKBAR_TEXT, res.data.message);
            }
          }).catch(console.error);

      },
    },

我的产品组件


import { EventBus } from "../../../event-bus";

 mounted() {
            EventBus.$on('update-discount', ($data) => {
                console.log($data);
            });
            this.getCategories();
            this.getProducts();
        },

我用不同的方法尝试了函数的回调,但没有结果,我在mount()中尝试了这个监听器,这没有帮助

【问题讨论】:

  • 尝试将其导入为 import EventBus from '@/eventBus'
  • 这个'@/eventBus'是什么意思?

标签: javascript laravel vue.js


【解决方案1】:

您可以在项目的src 文件夹中创建您的eventBus.js 文件,看起来像这样

import Vue from 'vue'
export default new Vue()

并尝试如下所示导入:

import EventBus from '@/eventBus'

或者这可能会帮助你https://alligator.io/vuejs/global-event-bus/

【讨论】:

  • 我有 event-bus.js,我导入它,代码在里面
  • 我的 event-bus.js 从 'vue' 导入 Vue; export const EventBus = new Vue();
  • 你可以试试以上一个吗。
  • 如果你的意思是尝试几种实现,那么在我的代码中我使用了很多,但是它不起作用
猜你喜欢
  • 2020-06-04
  • 2019-12-15
  • 2017-12-11
  • 2017-05-31
  • 1970-01-01
  • 2020-12-27
  • 2021-01-22
  • 1970-01-01
  • 2018-05-28
相关资源
最近更新 更多