Categories
Vue Answers

How to watch refs with Vue.js?

Spread the love

Sometimes, we want to watch refs with Vue.js.

In this article, we’ll look at how to watch refs with Vue.js.

How to watch refs with Vue.js?

To watch refs with Vue.js, we can watch the reactive properties in the ref if the ref is assigned to a component.

For instance, we write

<template>
  <div>
    <counter ref="counter" />
  </div>
</template>

<script>
export default {
  //...
  components: { Counter },
  mounted() {
    this.$watch(
      () => {
        return this.$refs.counter.i;
      },
      (val) => {
        console.log(val);
      }
    );
  },
  //...
};
</script>

to watch the counter‘s i reactive property.

Since we assigned the counter ref to the counter component, i is a reactive property in counter.

We call this.$watch with a function to return this.$refs.counter.i to watch the value.

And we have

(val) => {
  console.log(val);
};

to log the value of this.$refs.counter.i.

Conclusion

To watch refs with Vue.js, we can watch the reactive properties in the ref if the ref is assigned to a component.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.