设定:
我有多个Vue组件,每个组件在我的Web应用程序的不同对话框中都有多个实例。
对于每种类型的组件,我都有一个全局状态(下例中为handrailOptions
),以便每种类型的组件在对话框中保持同步。
我喜欢它,以便当组件超出第1步时,我会隐藏该对话框中的其他组件。
我使用计算机/手表组合很好地实现了这一点。
然而,我的问题是,如果我尝试通过超过1个Vue实例的计算来监听,它会劫持其他侦听器。
问题
以下是我正在使用的简化版本,当应用启动时,控制台记录'计算1' &安培; '计算2'。但是当我改变handrailOptions.step
时,只有第二次发射。 ('计算2'&'观看2')
有没有办法让多个Vues有一个计算的侦听器处理相同的值?
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');
}
}
});
答案 0 :(得分:1)
这可以按预期工作。我通过制作新handrailOptions
的数据对象使Vue
响应。像你一样,使它成为组件的数据对象也可以工作,但组件必须至少实例化一次。无论如何,为全局设置一个对象更有意义。
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>
&#13;