我见过
this question
两个都试过了
this.$parent
以及
this.$root
可供选择,但无济于事。情况如下。
App.vue
<template>
<div id="app">
<global-notifications/>
<router-view></router-view>
</div>
</template>
<script>
import GlobalNotifications from "./components/GlobalNotifications.vue"
export default {
name: "app",
components: {
GlobalNotifications
}
};
</script>
GlobalNotifications.vue
<template>
<div>
<p>Notifications:</p>
<p v-for="n in notifications" :key="n.id">{{ n }}</p>
<b-button @click="internalEmitter">Internal notification!</b-button>
</div>
</template>
<script>
export default {
data() {
return {
notifications: []
}
},
methods: {
appendNotification(n) {
this.notifications = [...this.notifications, n]
},
internalEmitter() {
let message = { id: `${Math.floor(Math.random()*1000000)}`, message: 'From the inside!' }
this.$emit('global-notification', message)
}
},
mounted() {
this.$on('global-notification', this.appendNotification)
},
beforeDestroy() {
this.$off('global-notification', this.appendNotification)
}
}
</script>
Dashboard.vue
通过路由器加载。是的,我试着直接从
应用程序.vue
<template>
<b-button @click="emitTheThing">External notification!</b-button>
</template>
<script>
export default {
methods: {
emitTheThing() {
let message = { id: `${Math.floor(Math.random()*1000000)}`, message: 'From the outside!' }
this.$emit('global-notification', message)
}
}
}
</script>
当我点击
Internal notification!
巴顿,我被炒鱿鱼了,一切都按预期进行。但是,当我点击
External notification!
如我所说,我试着发射
$parent
甚至在
$root
,但我只看到dev工具中的事件,在
<App>
和
<Root>
,分别是。然而
GlobalNotification
孩子似乎没有抓住他们。
我错过了什么?