Categories
Vue Answers

How to Watch Multiple Properties with a Single Handler in Vue.js?

Spread the love

Sometimes, we want to watch multiple properties with a single handler in Vue.js.

In this article, we’ll look at how to watch multiple properties with a single handler in Vue.js.

Watch Multiple Properties with a Single Handler in Vue.js

We can watch multiple properties with a single handler in Vue.js with the this.$watch method.

For instance, we can write:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      name: "jane",
      surname: "smith",
    };
  },
  mounted() {
    this.$watch(
      (vm) => [vm.name, vm.surname],
      (val) => {
        const fullName = this.name + " " + this.surname;
        console.log(fullName);
      },
      {
        immediate: true,
        deep: true,
      }
    );
  },
};
</script>

We name the name and surname reactive properties which we want to watch the values for.

And we do that by calling this.$watcg in the mounted hook with a function that returns an array with the reactive properties we want to watch.

vm is the component instance.

We get the values in function in the 2nd argument and we do what we want to it.

The 3rd argument is an object with some options.

immediate set to true means we watch the initial value of the reactive properties.

deep set to true means we watch for changes of properties in all levels of an object.

Conclusion

We can watch multiple properties with a single handler in Vue.js with the this.$watch method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *