Vue.js 3 this.$root.$on 不是函数

Vue.js 3 this.$root.$on is not a function

我有一个组件可以触发 this.$root.$emit('some-root-event') 喜欢

clickHandler: function() {
    this.$root.$emit("some-root-event", "aaaaaaaaaaaaaaaaaaaaaa");
    console.log('About $root.$emit')
}

里面的另一个组件应该捕获这个事件但抛出一个错误:

this.$root.$on is not a function

第二个组件的代码看起来像

mounted() {
    this.$root.$on("some-root-event", (data) => {
        console.log("About listener catch $root some-root-event"); console.log(data)
    })
}

有人可以帮助我了解问题出在哪里吗?

根据 Vue.js 3 中的 this RFC,他们删除了 $on$once$off 实例方法:

他们的动机 :

Vue 1.x implemented the component event system similar to that of AngularJS, with $dispatch and $broadcast where components in a tree can communicate by sending events up and down the tree. In Vue 2, we removed $dispatch and $broadcast in favor of a more state-driven data flow (props down, events up). With Vue 2's API, $emit can be used to trigger event handlers declaratively attached by a parent component (in templates or render functions), but can also be used to trigger handlers attached imperatively via the event emitter API ($on, $off and $once). This is in fact an overload: the full event emitter API isn't a part of the typical inter-component data-flow. They are rarely used, and there are really no strong reason for them to be exposed via component instances. This RFC therefore proposes to remove the $on, $off and $once instance methods

在 Vue 3 中,您可以为此使用外部库:https://v3.vuejs.org/guide/migration/events-api.html#_2-x-syntax

Vue 3 中不再有 $root space,因此您必须将事件总线模式与文档中提到的库一起使用。