gpt4 book ai didi

events - Vue this.$emit ('eventName' ) 组件 A 中的事件没有触发组件 B 中的 this.$on ('eventName' , callbackFunc) ,我是否放错了处理程序?

转载 作者:行者123 更新时间:2023-12-02 06:39:34 25 4
gpt4 key购买 nike

基本上,我有在创建时触发事件的组件和一个专门的“计数器”组件,用于对创建的组件进行计数,第二个组件与第一个组件并行存在。但是,当我尝试运行该应用程序时,计数器组件仅对自身进行计数,它似乎只检测在那里触发的创建事件。

我尝试将 this.$on() 操作移动到其他生命周期 Hook ,例如 Mounted() 但失败了。

组件A:

Vue.component('counter-component',{
template: `
<div class="card">
<div class="card-header">
Components:
</div>
<div class="card-body">
<p>Count: {{ totalCount }}</p>
<p>Enabled Count: {{ totalEnabledCount }}</p>
<p>Diabled Count: {{ totalDisabledCount }}</p>
</div>
</div>`,

created(){
this.$on('component-created', this.componentCreated),
this.$on('component-disabled', this.componentDisabled),
this.$on('component-enabled', this.componentEnabled),

this.$emit('component-created', 'counter-component');
},

data(){
return {
totalCount: 0,
totalDisabledCount: 0,
}
},

computed: {
totalEnabledCount(){
return this.totalCount - this.totalDisabledCount;
},
},

methods: {
componentCreated(data){
this.totalCount++;
},
componentDisabled(data){
this.totalDisabledCount++;
},
componentEnabled(data){
this.totalDisabledCount--;
}
}
});

组件B:

Vue.component('regular-component',{
template: `
<div class="my-2">
<div class="card" v-show="isVisible">
This is visible
</div>

<div class="card" v-show="!isVisible">
This is invisible
</div>
</div>`,

created(){
this.$emit('component-created', 'message-component');
},

data: () => {
return ({
isVisible: true,
});
},

methods: {
toggleVisibility(){
this.isVisible = !this.isVisible;

if(this.isVisible){
this.$emit('component-enabled','message-component');
} else {
this.$emit('component-disabled','message-component');
}
}
},
});

我原本希望两个组件都被计算在内,不幸的是只有包含处理程序的组件。

最佳答案

您似乎期望有一个可以发出并订阅的全局事件总线。
Vue 中默认情况并非如此,而是 Vue 使用严格的分层方法,其中事件从子级发送到父级,属性从父级传递到子级。默认情况下不打算进行同级组件之间的交互。

适合您的情况的正确方法是引入一个父组件来监听事件,将 totalCount 作为状态并将其作为属性传递给您的计数器显示组件:

<parent>
<regular-component v-on:component-created="totalCount++"/>
...
<counter-component v-bind:count="totalCount"/>
</parent>

关于events - Vue this.$emit ('eventName' ) 组件 A 中的事件没有触发组件 B 中的 this.$on ('eventName' , callbackFunc) ,我是否放错了处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098582/

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