Categories
Vue Answers

How to watch multiple properties with single handler with Vue.js?

Spread the love

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

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

How to watch multiple properties with single handler with Vue.js?

To watch multiple properties with single handler with Vue.js, we can use the this.$watch method.

For instance, we write


<script>
//...
export default {
  //...
  data() {
    return {
      name: "Alice",
      lastName: "Smith",
      fullName: "",
    };
  },
  mounted() {
    this.$watch(
      (vm) => [vm.name, vm.lastName],
      (val) => {
        this.fullName = `${this.name} ${this.lastName}`;
      },
      {
        immediate: true,
        deep: true,
      }
    );
  },
  //...
};
</script>

to call this.$watch with a function that returns the reactive properties we want to watch, a function that runs when any of the reactive properties change, and an object with some options.

We return an array of reactive properties we want to watch with

(vm) => [vm.name, vm.lastName]

And we so something with the values of the reactive properties when any of them change with

(val) => {
  this.fullName = `${this.name} ${this.lastName}`;
};

We set immediate to true to start watching the reactive properties when the component mounts.

And we set deep to true to watch all nested properties of each reactive property for changes.

Conclusion

To watch multiple properties with single handler with Vue.js, we can use 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 *