作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
基本上,我有在创建时触发事件的组件和一个专门的“计数器”组件,用于对创建的组件进行计数,第二个组件与第一个组件并行存在。但是,当我尝试运行该应用程序时,计数器组件仅对自身进行计数,它似乎只检测在那里触发的创建事件。
我尝试将 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/
我是一名优秀的程序员,十分优秀!