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.