如何从nuxt插件发出事件?

时间:2020-10-20 11:48:08

标签: javascript vue.js nuxt.js

代码:

export default ({ app }, inject: (key: string, value: any) => void) => {
  // doesn't work
  app.$emit('eventname', 'value')
})

我想从组件的插件发出事件。

app.$emit()引发错误app.$emit is not a function

1 个答案:

答案 0 :(得分:1)

查看nuxt插件文档后,我找到了解决此问题的可能方法。我将插件定义如下

plugins / hello.ts

import { Context } from '@nuxt/types';
import Vue from 'vue';

export default function (_ctx: Context, inject: Function) {
  const hello = function (this: Vue, msg: string) {
    console.log('emitting', msg);

    if (process.server) {
      console.log('server side');
    } else {
      console.log('client side');
    }

    setInterval(() => {
      this.$nuxt.$emit('hello', msg);
    }, 5000);
  } // Event Bus 
   .bind(new Vue());

  inject('hello', hello);
}

请注意,我使用匿名function(...){}而不是箭头函数() => {...}已更新请不要忘记bind(new Vue())事件总线,否则,如果您在vuex商店中调用this.$alertthis将是Store的实例,而不是预期的Vue

我正在按照以下步骤使用它

page / something.vue

...
mounted() {
    this.$hello('test');
    this.$nuxt.$on('hello', (val: string) => {
      alert(val);
    });
},
...

它按预期工作!当我使用打字稿时,我需要将this定义为Vue以避免this.$nuxt未定义错误。

在我的nuxt.config.js中

...
 plugins: [
    // '~/plugins/axios'
    { src: '~plugins/vuedraggable.ts' },
    { src: '~plugins/hello.ts' },
  ],
...

希望这可以对您有所帮助。

已更新:

如果您正在使用打字稿,并且想合并{Module Augmentation} $hello,使其在VueContext商店的Vuex实例中都可见,则可以包括在我们的案例plugins/hello.ts

中,这段代码与您的插件在同一文件中
declare module 'vue/types/vue' {
  // Vue instance this.$hello
  interface Vue {
    $hello(msg: string): void;
  }
}

declare module '@nuxt/types' {
  // NuxtAppOtions this.app.$hello
  interface NuxtAppOptions {
    $hello(msg: string): void;
  }
  // Accessible by Context
  interface Context {
    $hello(msg: string): void;
  }
}

declare module 'vuex/types/index' {
  // this.$hello inside Vuex stores
  interface Store<S> {
    $hello(msg: string): void;
  }
}

就是这样。