6

I'm building an aspect ration calculator. How can I avoid an infinite loop, if I have 4 variables that depend on each other?

I had to set 4 watchers, one for each data element.

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
}

I want the user to be able to change the ratios, and those changes should reflect on the pixels and update them. And of course he also has the option to change pixels, which reflect on the ratios.

Sammi
  • 286
  • 1
  • 3
  • 11

2 Answers2

2

Instead of watchers, you should use computed objects.

Here is basic example.

<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>
Onur Özkan
  • 918
  • 1
  • 10
  • 20
  • Computed properties didn't help me either. They also caused a stack overflow. The thing is, I want the user to be able to change the ratios, and those changes should reflect on the pixels and update them. And of course he also has the option to change pixels, which reflect on the ratios. – Sammi Jan 07 '18 at 22:31
  • Could you share your code on js fiddle? Usually $data doesnt get infitnite loops. It might be another code block triggering it. – Onur Özkan Jan 08 '18 at 10:58
0

can you not just return those 4 values as data in the component and because your using v-model, whenever the user changes those values, it calls a function which updates all of the calculations and it should update everything.

I would have thought computed properties/getters and setters would have worked.