我从我 app.vue
的曾孙之一发出自定义事件像这样的主要组件:
this.$emit('logged');
现在我想在我的 app.vue
中收听此事件主要组件,但我宁愿从 <script>
中的 javascript 来完成它标签比来自 <template>
:
<template>
<div>
<app-header></app-header>
<router-view></router-view>
<app-footer></app-footer>
</div>
</template>
<script>
import header from './components/shared/header.vue';
import footer from './components/shared/footer.vue';
export default {
components: {
'app-header': header,
'app-footer': footer
}
}
// can I listen to custom events somewhere here above?
</script>
是否可以在 vue 2 中监听来自 js 代码的自定义事件?我找不到这样的信息。
最佳答案
阅读Custom Events和 Non Parent-Child Communication在文档中。
从组件发出的事件不会向上冒泡超过一个级别,因此您将无法直接从主组件中监听曾孙组件发出的 logged
事件,除非您在每个级别向上代理事件。
或者,您可以使用事件总线进行非父子通信(参见上面的链接)。
这是您在代码中监听事件的方式:
<template>
<div>
<my-component ref="mycomp"></my-component>
</div>
</template>
<script>
export default {
mounted() {
// You need to have a reference to the component you want to listen to
// which is why I'm using refs here
this.$refs.mycomp.$on('logged', () => {
alert('Got logged event');
});
}
}
</script>
但实际上在上述情况下,您只需使用 v-on
。如果您使用的是事件总线,则需要使用 $on()
和 $off()
以编程方式。我不会解释事件总线模式,因为我确信它已经在 SO 上得到广泛讨论。
关于javascript - 在脚本标签 vue2 中监听来自 js 代码的自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915048/