How to avoid repetition listening to changes in the properties of a component?

Asked

Viewed 89 times

8

When I need to react to changes in N properties for the same callback I find myself wearing something like this:

watch: {
    propriedadeA(){
        this.reagir();
    },
    propriedadeB(){
        this.reagir();
    },
    propriedadeC(){
        this.reagir();
    }
}

Is there any way to be more DRY in this approach?

1 answer

8

this.$watch(vm => [vm.x, vm.y, vm.z].join(), val => {
  // ...
})

After writing the original answer (below), the creator of Vue.js suggested this way (above) even cleaner.

Original response:

I found a interesting solution here. Actually in this thread there is an idea plugin/ mixin, but I found this suggestion that I put down very simple and interesting.

Taking into account that Vue.js records which properties are accessed when a property computed is called we can rely on Vue.js to only run a method/property that is computed when one of its necessary values has changed.

So if we have something like return a, b, c; in a die computed the code will call a, b and c and Vue.js will record that computed need these values. And therefore will call/run this computed when the Setter one of these values change. To ensure that we can use this associated with a watch, just return Date.now() for example for the final value of that computed always be new/unique.

So we can do something like the example below and organize the code better:

new Vue({
  el: "#app",
  data() {
    return {
      mudancaConstante: 0,
      valorA: 0,
      valorB: 100,
      valorC: "constante",
      contadorABC: 0
    };
  },
  created() {
    setInterval(() => this.mudancaConstante++, 250);
    setInterval(() => this.valorA++, 2500);
    setInterval(() => this.valorB++, 1500);
  },
  // a parte interessante é daqui para baixo
  computed: {
    observadorABC() {
      return this.valorA, this.valorB, this.valorC, new Date();
    }
  },
  watch: {
    observadorABC() {
      this.contadorABC++;
    }
  }
});
<script src="//unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
  <p>this.mudancaConstante: {{mudancaConstante}}</p>
  <p>this.contadorABC: {{contadorABC}}</p>
</div>

  • forgot to accept your answer? hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.