gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:18:02 25 4
gpt4 key购买 nike

设置:

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

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

我希望这样,当一个组件超出步骤 1 时,我会在该对话框中隐藏其他组件。

我使用 computed/watch 组合很好地实现了这一点。

但是,我的问题是,如果我尝试通过超过 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>

关于javascript - 有没有办法让多个 Vue 有一个计算的监听器处理相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45471712/

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