有没有办法让多个 Vue 有一个计算的侦听器处理相同的值?



Setup:

我有多个 Vue 组件,每个组件在我的 Web 应用程序的不同对话框中有多个实例。

对于每种类型的组件,我都有一个全局状态(handrailOptions在下面的示例中(,以便每种类型的组件在对话框中保持同步。

我希望它,以便当组件超出步骤 1 时,我将其他组件隐藏在该对话框中。

我已经使用计算/手表组合很好地实现了这一点。

但是,我的问题是,如果我尝试通过多个 Vue 实例进行计算,它似乎会劫持其他侦听器。

问题

下面是我正在使用的内容的简化版本,当应用程序启动时,控制台会记录"计算 1"和"计算 2"。但是当我换handrailOptions.step时,只有第二个火了。("计算 2"和"观看 2"(

有没有办法让多个 Vue 有一个计算的侦听器处理相同的值?

handrailOptions = {
step: 1
};
Vue.component( 'handrail-options', {
template: '#module-handrail-options',
data: function() {
return handrailOptions;
},
});
var checkoutDialog = new Vue({
el: '#dialog-checkout',
computed: {
newHandrailStep() {
console.log('computed 1');
return handrailOptions.step;
}
},
watch: {
newHandrailStep( test ) {
console.log('watched 1');
}
}
});
new Vue({
el: '#dialog-estimate-questions',
computed: {
newHandrailStep() {
console.log('computed 2');
return handrailOptions.step;
}
},
watch: {
newHandrailStep( test ) {
console.log('watched 2');
}
}
});

这按预期工作。我通过制作新Vue的数据对象使handrailOptions响应。像您所做的那样,使其成为组件的数据对象也可以工作,但该组件必须至少实例化一次。无论如何,为全局对象使用单个对象更有意义。

handrailOptions = {
step: 1
};
// Make it responsive
new Vue({data: handrailOptions});
var checkoutDialog = new Vue({
el: '#dialog-checkout',
computed: {
newHandrailStep() {
console.log('computed 1', handrailOptions.step);
return handrailOptions.step;
}
},
watch: {
newHandrailStep(test) {
console.log('watched 1');
}
}
});
new Vue({
el: '#dialog-estimate-questions',
computed: {
newHandrailStep() {
console.log('computed 2', handrailOptions.step);
return handrailOptions.step;
}
},
watch: {
newHandrailStep(test) {
console.log('watched 2');
}
}
});
setInterval(() => ++handrailOptions.step, 1500);
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="dialog-estimate-questions">
Main step {{newHandrailStep}}
</div>
<div id="dialog-checkout">
CD step {{newHandrailStep}}
</div>

最新更新