Vue.js 中的兄弟组件之间的事件,为什么要在 $root 上注册它们?
Events between sibling components in Vue.js, why register them on the $root?
我刚刚浏览了一些 Vue.js 代码 here 并注意到模态组件中的一些代码如下所示:
mounted () {
this.$root.$on('habitica:update-challenge', (data) => {
if (!data.challenge) return;
this.cloning = false;
this.$store.state.challengeOptions.workingChallenge = Object.assign({}, this.$store.state.challengeOptions.workingChallenge, data.challenge);
this.$root.$emit('bv::show::modal', 'challenge-modal');
});
}
如果您移动到 s 兄弟组件 here 中的一行,您基本上会看到一个兄弟组件调用 edit()
函数,基本上就是下面的函数:
edit () {
this.$root.$emit('habitica:update-challenge', {
challenge: this.challenge,
});
}
因此,如果我是对的,事件将在 challengeModal
内的 this.$root
组件上注册,然后使用 this.$root.$emit
在 challenDetail
组件内注册?我的类比对吗?
几个次要问题:challenge: this.challenge,
是被发送到 this.$root
的有效负载,并且 challenge: this.challenge,
在 this.$root.$on('habitica:update-challenge', (data) => {
中以参数的形式被接收,即data
?
P.S。我来自 ReactJS/jQuery 背景,所以我只是想了解 Vue 事件。
你的假设是正确的。
Vue 事件是从 AngularJS 借来的,事件 API 在 Vue 2 中进一步改变。概念是 similar 到 DOM 或其他 JavaScript 事件实施:
Note that Vue’s event system is different from the browser’s EventTarget API. Though they work similarly, $emit, $on, and $off are not aliases for dispatchEvent, addEventListener, and removeEventListener.
兄弟姐妹应该通过公共 parent 进行通信,$root
实例充当全局事件总线。事件侦听器在一个组件内注册并在另一个组件内触发。
我刚刚浏览了一些 Vue.js 代码 here 并注意到模态组件中的一些代码如下所示:
mounted () {
this.$root.$on('habitica:update-challenge', (data) => {
if (!data.challenge) return;
this.cloning = false;
this.$store.state.challengeOptions.workingChallenge = Object.assign({}, this.$store.state.challengeOptions.workingChallenge, data.challenge);
this.$root.$emit('bv::show::modal', 'challenge-modal');
});
}
如果您移动到 s 兄弟组件 here 中的一行,您基本上会看到一个兄弟组件调用 edit()
函数,基本上就是下面的函数:
edit () {
this.$root.$emit('habitica:update-challenge', {
challenge: this.challenge,
});
}
因此,如果我是对的,事件将在 challengeModal
内的 this.$root
组件上注册,然后使用 this.$root.$emit
在 challenDetail
组件内注册?我的类比对吗?
几个次要问题:challenge: this.challenge,
是被发送到 this.$root
的有效负载,并且 challenge: this.challenge,
在 this.$root.$on('habitica:update-challenge', (data) => {
中以参数的形式被接收,即data
?
P.S。我来自 ReactJS/jQuery 背景,所以我只是想了解 Vue 事件。
你的假设是正确的。
Vue 事件是从 AngularJS 借来的,事件 API 在 Vue 2 中进一步改变。概念是 similar 到 DOM 或其他 JavaScript 事件实施:
Note that Vue’s event system is different from the browser’s EventTarget API. Though they work similarly, $emit, $on, and $off are not aliases for dispatchEvent, addEventListener, and removeEventListener.
兄弟姐妹应该通过公共 parent 进行通信,$root
实例充当全局事件总线。事件侦听器在一个组件内注册并在另一个组件内触发。