gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:48:01 30 4
gpt4 key购买 nike

我有一个触发 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)
})
}
有人可以帮助我了解问题出在哪里吗?

最佳答案

根据this RFC在 Vue.js 3 中,他们删除了 $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

关于javascript - Vue.js 3 this.$root.$on 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63622303/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com