代码:
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
实例、Context
和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;
}
}
就是这样。
关于javascript - 如何从 nuxt 插件发出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64444511/