[英]how to use the eventHub in Nuxt?
How to use the eventHub on Nuxt.js?如何在 Nuxt.js 上使用 eventHub?
we usually set on eventHub in main.js just like this:我们通常在 main.js 中设置 eventHub,如下所示:
export default {
name: "App",
data() {
return {
eventHub: new Vue()
};
},
provide() {
return {
eventHub: this.eventHub
};
}
};
now problem is nuxt doesn't main.js, how do I configure eventHub in nuxt?现在的问题是 nuxt 没有 main.js,如何在 nuxt 中配置 eventHub?
@Guillermo s Solution should work. @Guillermo 的解决方案应该有效。 However, you do not have to use a plugin.
但是,您不必使用插件。 Instead, you can use
$nuxt.$emit
.相反,您可以使用
$nuxt.$emit
。 It does the same as what Guillermo suggests but does not require you to register a plugin.它与 Guillermo 建议的相同,但不需要您注册插件。
Just register a listener in one Component:只需在一个组件中注册一个监听器:
// Code in a Component
beforeMount() {
this.$nuxt.$on('my-event', () => { console.log("Hello!")});
}
Now you can fire events in another Component and the first one will listen for them.现在您可以在另一个组件中触发事件,第一个组件会监听它们。 You can fire these Events like so:
您可以像这样触发这些事件:
// Code in some other Component
methods() {
letComponentSayHello() {
this.$nuxt.$emit("my-event");
}
}
If you need to fire an event after a Component is mounted, make sure you register the listener in your beforeMounted()
-Hook.如果您需要在安装组件后触发事件,请确保在
beforeMounted()
-Hook 中注册侦听器。 This was also suggested here https://stackoverflow.com/a/64717957/11930769 .这也被建议在这里https://stackoverflow.com/a/64717957/11930769 。
I was not able to find something on the Docs about this.我无法在文档上找到有关此的内容。 Nonetheless, here is an article that suggests to use the
$nuxt.$emit
.尽管如此,这里有一篇文章建议使用
$nuxt.$emit
。 https://medium.com/@aneesshameed/event-bus-in-nuxt-7728315e81b6 https://medium.com/@aneesshameed/event-bus-in-nuxt-7728315e81b6
The easiest way you can achieve this in Nuxt is by creating a custom plugin that injects your event hub.在 Nuxt 中实现这一点的最简单方法是创建一个自定义插件来注入您的事件中心。
Create a file called 'eventHub.js' in the 'plugins/' directory在“plugins/”目录中创建一个名为“eventHub.js”的文件
import Vue from 'vue'
export default (context, inject) => {
const $eventHub = new Vue()
inject('eventHub', $eventHub)
}
Now, in your 'nuxt.config.js' register the plugin现在,在您的“nuxt.config.js”中注册插件
plugins: [
{ src: '~/plugins/eventHub.js' },
],
And you are good to go: You can use it from inside any Vue component referencing it like this:你对 go 很好:你可以在任何引用它的 Vue 组件中使用它,如下所示:
// Event Listen
this.$eventHub.$on('test-event', () => {})
// Event Emit
this.$eventHub.$emit('test-event')
You will have also have the $eventHub object available in Nuxts 'context' object and from any mutation or action in the store (although I would be cautious about using it in that way).您还将在 Nuxts 'context' object 以及商店中的任何突变或操作中获得 $eventHub object 可用(尽管我会谨慎地以这种方式使用它)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.