我正在构建一个纵横比计算器。 如果我有 4 个相互依赖的变量,如何避免无限循环?
我必须设置 4 个观察者,每个数据元素一个。
watch: {
widthRatio(value) {
this.pxWidth = (value * this.pxHeight) / this.heightRatio;
},
heightRatio(value) {
this.pxHeight = (value * this.pxWidth) / this.widthRatio;
},
pxWidth(value) {
//sets heightRatio and widthRatio
},
pxHeight(value) {
//sets heightRatio and widthRatio
}
我希望用户能够更改比率,这些更改应该反射(reflect)在像素上并更新它们。当然,他也可以选择更改反射(reflect)比率的像素。
最佳答案
您应该使用计算对象而不是观察者。
这是基本示例。
<script src="https://vuejs.org/js/vue.js"></script>
<div id="app">
<strong>Ratio</strong>: {{whRatio}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: { width: 16, height: 9 },
computed: {
whRatio () {
return this.width / this.height
}
}
});
</script>
关于javascript - Vue.js 观察者触发无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140958/