javascript - 如何从 nuxt 插件发出事件?

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

最佳答案

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

插件/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.$alert this 将是 Store 的实例,而不是预期的 Vue。

我正在使用它作为后续

页面/something.vue

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

它按预期工作!因为我正在使用 typescript ,所以我需要将 this 定义为 Vue 以避免 this.$nuxt is not defined 错误。

在我的 nuxt.config.js 中

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

我希望这能以某种方式帮助你。

更新:

如果你正在使用 typescript 并且想要合并(模块增强)$hello 以便它在 Vue 实例、ContextVuex 存储,在我们的例子中,您可以将这段代码包含在您的插件的同一文件中 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;
  }
}

就是这样。

关于javascript - 如何从 nuxt 插件发出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64444511/

相关文章:

javascript - 根据用户选择更新下拉菜单值

javascript - 对 d3 树中最右/最左表兄弟节点的最有效访问

javascript - 无法理解为什么它给我 : Uncaught (in promise) TypeError: Cannot read property 'blabla' of undefined

laravel - 视觉 : Is there a way to detect changes data coming from API

javascript - 我们可以将 SPA 概念与 Nuxt.js 中的动态嵌套路由结合起来吗?

javascript - Nuxt 根据 .json 文件数据生成动态页面

javascript - 如何在 IE-8 Javascript 的函数体中绑定(bind) "this"?

vue.js - 如何对对象数组进行 v-model

javascript - Vue.js - 我的多 Accordion 菜单组件无法通过切换标志工作

javascript - Vue编辑已作为prop传递给组件的v-data