Buy Me A Coffee 😇

VueJs watch multiple properties

/ Let us look at how we can watch multiple properties using VueJs 3 and VueJs 2. Watching multiple items is really useful, especially when working with a lot of data.

#VueJS
Apr. 20, 2023. 1:06 AM

So, for those people who are trying to find a way to watch multiple properties using a single handler in VueJS. Here are some ways you can do it.

For Vue 3

We can declare variables we want to watch, in this example we have itemA and itemB. in Vue 3 we can use an array in the watch function first argument to watch those variables.

import { watch, ref } from "vue"

export default {
  setup(() => {
    const itemA = ref(1);
    const itemB = ref('hello');

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

Vue 2

In vue 2 we have to use the old setup. We declared our variable in data property. We then created a computed property were we add itemAitemBProperties to get the computed value of this items. Then we created a watch to watch the computed value.

    export default {
      data() {
        return {
           itemA: 1,
           itemB: 'text'
        }
      }
      computed: {
        itemAitemBProperties() {
          return [this.itemA, this.itemB];
        },
      },
      watch: {
        propertyAAndPropertyB(newVal, oldVal) {
          console.log(newA, newB);
        },
      },
    }

Conclusion

The idea above is just a sample, but you can modify it, and its up to you how you can manipulate your data. In Vue 3 its good to add your properties into an array and watch it. in Vue 2 leverage the computed properties.


If you enjoy this article and would like to show your support, you can easily do so by making a donation through Ko-fi. Your contribution is greatly appreciated!

Buy Me a Coffee at ko-fi.com
BroJenuel
Hi! 👋 Im Jenuel. Since the beginning of my journey as a software developer 6 years ago, I've done office and remote work for companies, and collaborated with teams of developers to build and maintain awesome products. I'm quietly confident, naturally curious, and perpetually working on improving my craft.
Living, learning, & leveling up one day at a time.
Hand Crafted by Me @ 2023