- read

Vuejs Tip: Deep Watching Elements

John Philip 48

Vuejs Tip: Deep Watching Elements

A Simplified Approach to Deeply Watching Lists, Dictionaries, and More

John Philip
Level Up Coding
Published in
3 min read22 hours ago

--

Photo by Pim Chu on Unsplash

Vue.js provides the watch API property. The watch property allows you to monitor changes in the values of properties, and when a change occurs, it invokes a specified callback function.

Setting up a watcher

To set up a watcher in Vue.js, we use the watch API function, which takes two arguments. The first argument is the element to be watched, and the second argument is the callback function triggered when the watch detects a change.

The syntax is as follows:

import { watch, ref } from 'vue';

const question = ref('');

watch(question, (newQuestion, oldQuestion) => {
// The callback function is triggered when 'question' changes.
});

Our Sample Watch Example

<script setup>
import { reactive, watch } from 'vue';

const person = reactive({
name: '',
hobbies: [],
});

function addHobby() {
person.hobbies.push('Cycling');
}

watch(person, (newValue, oldValue) => {
console.log(`Value changed from ${JSON.stringify(oldValue)} to ${JSON.stringify(newValue)}`);
});

Here’s why it behaves this way:

  • Shallow Watching by Default: Vue.js uses a shallow watcher by default to optimize performance. It watches for changes in the reference of a property, so when you reassign a completely new object or array to a variable, the watcher detects the change because the reference has changed. However, it doesn’t automatically watch the individual properties or elements inside these objects or arrays.
  • Avoiding Unnecessary Recursion: Deep watching every nested property or element in complex data structures can be computationally expensive and lead to performance issues, especially in large applications. Vue.js provides the deep option to allow developers to specify when they want to watch nested properties explicitly, preventing unnecessary recursion in most cases.

To watch deeply nested properties or elements within dictionaries and lists, you should use the deep: true option. This option tells Vue.js to recursively traverse the nested data structure and watch for changes at all levels…