116

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

JrmDel
  • 390
  • 1
  • 4
  • 16
rahulserver
  • 10,411
  • 24
  • 90
  • 164
  • 2
    Depends on how your data are structured.If you put watched data in one object you can watch that single object with deep: true property, and triger that method.Also you can watch whole data object but I don't suggest to do that. – Belmin Bedak Mar 11 '17 at 15:43
  • I dont think there is some way as discussed [here](https://github.com/vuejs/vue/issues/844), You can create a computed property as done [here](https://jsfiddle.net/kmj6Lsae/3/) but that also is not very clean. – Saurabh Mar 11 '17 at 16:23

9 Answers9

185

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('|');
Avraham
  • 916
  • 1
  • 13
  • 25
Yi Feng Xie
  • 4,378
  • 1
  • 26
  • 29
  • 2
    As of your April update, I am interesting in using this approach, but am unable to find the documentation as I am unable to get the syntax just right, only found the docs of [v2](https://vuejs.org/v2/api/#watch) and of [v3](https://v3.vuejs.org/api/instance-methods.html#watch), but these both do not show the syntax I need. Need the syntax for: `export default { watch:{ --watcher for multiple props here-- } }` – LMB Aug 12 '20 at 09:53
  • Using vue 2 and composition-api plugin, It works with a function returning an array of values to watch: `watch(() => [a, b], ....)` – Finrod Jan 06 '21 at 16:01
  • Using vue 2, I get [Object object] when I console any of the properties I get in the watch method. I guess it's not working? – aasutossh Apr 25 '21 at 03:40
  • @aasutossh The answer coerces it into a string. If you need to have any other types, best would be to return an object from the computed property. `startAndEnd() { const {start, end} = this; return { start, end }; },`. You can then use the different values in their corect type with newVal.start and newVal.end for example. You must make sure to emit a newly created Object each time so you don't get mutated objects in your oldVal. – Excalibaard Jul 09 '21 at 09:44
  • 1
    I'm using 3.0. I have a long list of variables that I want to watch, but I don't care about the values of them. How can I write my watch statement and not include the variable values? I haven't had any luck coming up with a syntax and there doesn't seem to be any documentation on this. – user842818 Oct 08 '21 at 19:48
37

Another possibility:

new Vue({
  el: '#app',
  data: {
    name: 'Alice',
    surname: 'Smith',
    fullName: '' // IRL you would use a computed for this, I'm updating it using a watch just to demo how it'd be used
  },
  mounted() {
    this.$watch(vm => [vm.name, vm.surname], val => {
      
      this.fullName = this.name + ' ' + this.surname;
      
    }, {
      immediate: true, // run immediately
      deep: true // detects changes inside objects. not needed here, but maybe in other cases
    }) 
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    name:<input v-model="name">
  </div>
  <div>
    surname:<input v-model="surname">
  </div>
  <div>
    full name: {{ fullName }}
  </div>
</div>

More info on the Vue API docs for vm.$watch.

tony19
  • 125,647
  • 18
  • 229
  • 307
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • This was super helpful to me, however it should be noted that I was watching an array of objects and for that I needed to add `{deep: true}` The official Vue JS Docs are actually quite helpful on this subject: https://vuejs.org/v2/api/#vm-watch – John Mellor Oct 25 '19 at 05:47
  • 1
    @JohnMellor alright, good to know. I added the link and the `deep: true` in the example above, just in case – acdcjunior Oct 25 '19 at 20:29
  • This is super cool, thanks for sharing!! – Steve Bauman Oct 18 '21 at 17:13
  • Using TypeScript, I get an error saying "no overload matches this call". Any ideas how to solve that please? – Oli Mar 02 '23 at 12:06
30

like this:

data() {
  return {
    propa: '',
    propb: ''
  }
},
computed: {
  changeData() {
    const { propa, propb } = this
    return {
      propa,
      propb
    }
  }
},
watch: {
  changeData: {
    handler: function(val) {
      console.log('value change: ', val)
    },
    deep: true
  }
}
gold three
  • 661
  • 1
  • 8
  • 10
  • 3
    You can simply return an array of items to track. `changeData() { return [this.propa, this.propb] }` – Steven Spungin Jan 28 '21 at 17:42
  • 2
    This is the best answer. Retains type and is simple to implement without this.$watch. Array would work as well, but by returning an object you keep the names of each property intact, instead of having to rely on indices. – Excalibaard Jul 09 '21 at 09:49
  • This should be marked as the correct answer for vue2. – FloG Sep 14 '21 at 22:07
8

First, your definition could be simplified. doSomething does not appear to be a method on the Vue, so your watch could just be

watch:{
    propa: doSomething,
    propb: doSomething
}

Second, sometimes it's important to remember Vue definition objects are just plain javascript objects. They can be manipulated.

If you wanted to watch every property in your data object, you could do something like this

function doSomething(after, before){
  console.log(after,before);
}

function buildWatch(def){
  if (!def.watch)
    def.watch = {};
  for (let prop of Object.keys(def.data))
    def.watch[prop] = doSomething;
  return def;
}

let vueDefinition = {
  data:{
    propa: "testing",
    propb: "testing2",
    propc: "testing3"
  }
}

export default buildWatch(vueDefinition)

If you wanted to watch only some defined list of your properties:

// First argument is the definition, the rest are property names
function buildWatch(def){
  if (!def.watch)
    def.watch = {};
  const properties = Array.prototype.slice.call(arguments,1); 
  for (let prop of properties)
    def.watch[prop] = doSomething;
  return def;
}

export default buildWatch(vueDefinition, "propa", "propb")
Bert
  • 80,741
  • 17
  • 199
  • 164
5

For Vue typescript you can do like this. Tested.

  @Watch('varA')
  @Watch('varB')
  private oneOfAboveChanged(newVal) {
    console.log(newVal)
  }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Binh Ho
  • 3,690
  • 1
  • 31
  • 31
5

My resolution for vue2:

export default {
  data() {
    return {
      status: null,
      name: null,
      date: null,
      mobile: null,
      page: 1,
    }
  },
  watch: {
    ...["status", "name", "date", "mobile", "page"].reduce((acc, currentKey) => {
      acc[currentKey] = (newValue) => {
        // doSomething
        // console.log(newValue, currentKey)
      }
      return acc
    }, {}),
  }
}
Mac Chow
  • 51
  • 1
  • 2
4

vm.$data

If you want to listen to all the properties inside data(), you can use this.$data

<script>
export default {
  data () {
    return {
      propA: 'Hello',
      propB: 'world'
    }
  }
  watch: {
    $data (newValue) { // Watches for any changes in data()
      // Do something with the new data
    }    
  }
}
</script>
W4G1
  • 1,337
  • 1
  • 11
  • 15
1

Old question but the answer still may be useful for those who are still working in vue 1.

You can watch multiple props by wrapping them in quotes:

data() {
   return {
      foo: {
         prop1: 1,
         prop2: 2,
      }
   }
}
watch: {
    '[foo.prop1, foo.prop2]'(newVal, oldVal) {
        //do sth
        console.log(newVal); // prints ([prop1, prop2])
        console.log(oldVal); // prints ([prop1, prop2])
    }
}
konradz
  • 23
  • 1
  • 8
0

If someone is looking for this in 2023 and is using Vue3, another possibility and a better option is to just use watchEffect.

https://vuejs.org/api/reactivity-core.html#watcheffect