【问题标题】:NuxtJS and event busNuxtJS 和事件总线
【发布时间】:2022-11-11 22:54:28
【问题描述】:

我正在尝试从 nuxt 中的实例属性创建一个事件,但是该事件未发出或接收。

plugins/internal/bus.js

import Vue from 'vue';

const eventBus = {}

eventBus.install = function (Vue) {
  Vue.prototype.$bus = new Vue()
}

Vue.use(eventBus)

plugins/internal/index.js

import Vue from 'vue';

export default function (_ctx, inject) {
  const notify  = function (msg) {

    console.log('emitting', msg);

    setInterval(() => {
      this.$bus.$emit('add', msg);
    }, 500);
  }
   .bind(new Vue());

  inject('notify', notify);
}

nuxt.config.js

  plugins: [
    '~/plugins/internal/bus.js',
    '~/plugins/internal/index.js',
    ...
  ]

在我的组件中,

  mounted() {
    this.$bus.$on('add', (val) => {
      console.log(val);
    })
    this.$bus.$on('close', this.onClose)
  },

执行this.$notify({ foo: 'bar' }),正确调用实例属性,但是事件未发出或未接收,坦率地说不知道如何调试它。我在这里想念什么?

【问题讨论】:

  • 要调试它,请使用 Vue 开发工具。您将能够看到发出的内容。顺便说一句,你为什么使用事件总线? Vuex 更干净,更易于跟踪(因此是调试)。你的代码看起来很复杂,有什么原因吗?如果您的问题无法使用 Vuex 解决,我可能会为您链接一篇演讲/文章,解释如何在 Nuxt 中正确实现它。
  • 好吧,接下来我将尝试使用 Vuex,尽管我不介意看一下上述文章。
  • 谢谢,会看看的。我找不到太多关于使用 Vuex 调度某种事件的信息,是否有相关资源?
  • official documentation 仍然是最好的去处。

标签: javascript vue.js events vuejs2 nuxt.js


【解决方案1】:

最后,问题来自未正确注册的组件 (Notification)。

【讨论】:

    【解决方案2】:

    Você não precisa desenvolver um Event Bus。 O NuxtJS possui um 事件总线 nativo。

      // $emmit
      methods: {
        displaySearchbar() {
          this.$nuxt.$emit('display-searchbar', true)
        },
      },
    
      // $on
      mounted() {
        this.$nuxt.$on('display-searchbar', (display) => {
          this.displaySearchbar = display
        })
      },
      beforeDestroy() {
        this.$nuxt.$off('display-searchbar')
      },
    

    Espero ter ajudado! Nesse artigo você entenderá melhor: https://aneesshameed.medium.com/event-bus-in-nuxt-7728315e81b6

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2023-01-26
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多