如何在nuxt布局中监听页面$emit? [英] How to listen for a page $emit in a nuxt layout?
问题描述
Nuxt 2.15.6; 我想通过在我的根布局中动态切换菜单组件来切换我的菜单组件的布局.
Nuxt 2.15.6; I want to switch the layout of my menu component by dynamically switching menu components in my root layout.
default.vue
<template>
<component :is="navLayout"></component>
<Nuxt :navLayout="navLayout = $event" />
</template>
data() {
return {
navLayout: "default"
};
},
在孩子"中的组件,我的页面,例如.login.vue (/login) 我$emit
一个事件;
In the "child" components of , my pages eg. login.vue (/login) I $emit
an event;
...
import nav2 from "@/layouts/nav2";
...
created() {
this.$emit("navLayout", nav2);
},
现在似乎是
组件无法捕获事件.我还尝试调用 <Nuxt @navLayout="test()";/>
方法.
Now it seems to be the <Nuxt>
component is not able to catch the event. I also tried calling a <Nuxt @navLayout="test()" />
method.
如何避免 this.$root.$emit(...);
在我的 login.vue
和
How can I avoid this.$root.$emit(...);
in my login.vue
and
this.$root.$on("navLayout", navLayout => {
this.navLayout = navLayout;
});
在default.vue
?
推荐答案
这个答案很好用,因为它看起来你现在不能做:https://github.com/nuxt/nuxt.js/issues/8122#issuecomment-709443008
This answer works fine as it looks like you cannot do it right now: https://github.com/nuxt/nuxt.js/issues/8122#issuecomment-709443008
在子组件中
<button @click="$nuxt.$emit('eventName', 'nice payload')">nice</button>
在默认布局上
<script>
export default {
created() {
this.$nuxt.$on('eventName', ($event) => this.test($event))
},
methods: {
test(e) {
console.log('test ok >>', e)
},
},
}
</script>
在 Nuxt
上设置监听器本身不起作用.
<Nuxt @navLayout="navLayout = $event" :navLayout="navLayout" />
我可以看到事件发生并且侦听器插入到
但它不会触发侦听器的任何方法...
I can see the event go and the listener plugged to <nuxt></nuxt>
but it does not trigger any method with the listener...
PS:至少适用于
.
PS: works for <nuxt-child></nuxt-child>
at least.
这篇关于如何在nuxt布局中监听页面$emit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!