Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js watchers trigger an inifinite loop

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.

like image 493
Sammi Avatar asked Oct 28 '22 21:10

Sammi


1 Answers

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>
like image 91
Onur Özkan Avatar answered Nov 15 '22 05:11

Onur Özkan