vue js watch multiple properties with single handler

rahulserver picture rahulserver · Mar 11, 2017 · Viewed 46.5k times · Source

Currently I have to watch a few properties. And if each of them changes, I have to invoke the same function:

export default{
  // ...... rest of code 
  watch: {
    propa: function(after,before) {
      doSomething(after,before);
    },
    propb: function(after,before) {
      doSomething(after,before);
    }
    // ... so on
  }
}

So I am having to write the same code multiple times above. Is it possible to simply have all properties being watched and invoke their change handler without having to write same code multiple times?

PS: I am using vue 1.x

Answer

Yi Feng Xie picture Yi Feng Xie · Aug 24, 2017

Update: April-2020

For people who are using Vue 3, the watch API can accept multiple sources

import { watch, ref } from 'vue';

export default {
  setup(() => {
    const a = ref(1), b = ref('hello');

    watch([a, b], ([newA, newB], [prevA, prevB]) => {
      // do whatever you want
    });
  });
};


Original answer for Vue 2

there is no official way to solve your question(see this). but you can use the computed property as a trick:

    export default {
      // ...
      computed: {
        propertyAAndPropertyB() {
          return `${this.propertyA}|${this.propertyB}`;
        },
      },
      watch: {
        propertyAAndPropertyB(newVal, oldVal) {
          const [oldPropertyA, oldProvertyB] = oldVal.split('|');
          const [newPropertyA, newProvertyB] = newVal.split('|');
          // doSomething
        },
      },
    }

if you just want to do something and don't care about what's new/old values. ignore two lines

    const [oldPropertyA, oldProvertyB] = oldVal.split('|');
    const [newPropertyA, newProvertyB] = newVal.split('|');