代码:
export default ({ app }, inject: (key: string, value: any) => void) => {
// doesn't work
app.$emit('eventname', 'value')
})
我想从组件的插件发出事件。
app.$emit()
引发错误app.$emit is not a function
答案 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.$alert
,this
将是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
,使其在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;
}
}
就是这样。