When it comes to the computation of nested or deep data types like arrays or objects, Vue.js or any other programming language does not automatically detect the hierarchical change in the data. However, we all know that Vue.js provides the watch and computed properties to perform some change variables.
- But when it comes to nested data changes, Vue.js does not detect that.
- This post will learn to perform some changes by watching the nested data of arrays or objects.
- Before learning about watching nested data in Vue.js, let’s first understand how the watch property works?
The watch property is used to watch a variable and allows the user to perform some desired tasks on the variable’s change. For example, at the change of some variable, we want to console something.
The syntax for writing such code in Vue will go like this:.
This is a testing page
- Now, this code is supposed to display the change in the quantity of the object.
- But, when we execute the code and click the button on the web page:.
You can see in the above gif; nothing is happening in the console. The reason behind this is that the watcher does not look deep into the values of the objects, and this is the real problem to which we are going to solve now. Vue.js provides the deep property for watching deep down into the values of objects and arrays. The syntax for using the deep property and watching the nested data is as follows:.
In this syntax, we have set the deep property to true and rearranged the handler() function. Now, after changing the code, if we reload the web page and click on the button:.
Here you can see that the watcher is working and displaying the message in the console.
After reading this post, watching and computing deep or nested data structures in Vue.js is not difficult anymore.
We have learned how to watch the change of a value in an object or array and execute some tasks with the help of the “deep” property of Vue.js.
In this series, I'm focusing on the basics needed to start working in Vue 3 for people who might have some experience in Vue 2, but who haven't yet built anything in Vue 3. Check out my previous posts in the series:. Today, I'll introduce how to use methods, watch, and computed in Vue 3, and I'll also give a general comparison of watch and the new watchEffect.
The way I learn best is by connecting abstract concepts to a real world situation, so I tried to think of a simple, realistic situation for using methods, watch, and computed.
The situation would need to demonstrate the following:. doing something to data properties to change them (using methods).
making something else occur (i.e, a side effect) because of a change to the data properties (using watch).
returning a value that is calculated based on data properties that have been changed (computed). I will use a real-world example of a company with employees and managers; the logic will help keep track of number of employees, number of managers, and total company headcount. Not the most exciting example, but I really just want to keep it simple.
One of the first things I need to be able to do, whether I'm using Vue 2 or Vue 3, is be able to make stuff happen with methods/functions (note: I'm using the terms functions and methods interchangeably in this section).
The magic of Vue is its reactivity, so local state updates automatically as stuff happens.
The stuff that happens is often triggered by methods.
In my real-world example, I want to create a component that has a variable to represent the number of employees with buttons I click to add or subtract the number of employees, changing the headcount.
I'll write functions to perform these basic actions. Here's what the rendered component looks like:. I am familiar with the Vue 2 way of adding functions to the component: add each function to the methods object:.
And the following line from the template shows that Vue 2 and Vue 3 are no different in how the methods are invoked in the template:.
Watching nested data — Arrays and Objects
However, Vue 3 is different now in regards to where we write the methods in the script.
In Vue 3, I can now write my functions inside the setup function, which runs very early in the component lifecycle (before the component instance is even created).
I no longer have to write all my functions in the methods property of the options API. In this example, I have written two basic functions, and those functions are not separated into a separate methods block like in Vue 2, they are inside setup with the related logic like the variable for numEmployees.
What is a watch method?
I can make the functions available to the template by returning an object that includes them:.
Notice that there is no keyword this when referring to numEmployees. Methods that are inside the setup function no longer use the keyword this to refer to properties on the component instance since setup runs before the component instance is even created.
I was very used to writing this-dot everything in Vue 2, but that is no longer the experience in Vue 3.
- The use of ref() surrounding the data property is something I introduced in the last post, and it's important here. For reactivity to work in Vue, the data being tracked needs to be wrapped in an object, which is why in Vue 2, the data method in the options API returned an object with those reactive data properties.
- Now, Vue 3 uses ref to wrap primitive data in an object and reactive to make a copy of non-primitive data (I've only introduced ref so far in this series). This is important to methods because it helps me understand why I see numEmployees.value inside the function rather than just numEmployees.
- I have to use .value to reach the property inside the object created by ref and then perform the action on that value property. (I don't have to use the .value property in the template, however.
Just writing numEmployees grabs the value). Writing all the methods inside the setup function may seem like it would get messy when there is more complexity going on in the component, but in practice, related logic could all be grouped together to run within its own function.
This is where Vue 3 starts to show its strengths.
I could group all the logic for updating headcount into a function called updateHeadcount, then create a separate JS file where that logic lives.
I'll actually name it useUpdateHeadcount.js, which is Vue 3 best-practice for naming this type of file (the convention of starting composables with use is discussed in the Composition API RFC in this section).
Here's the useUpdateHeadcount.js file:. Now, in my component, I just have to write this in the setup function:. Notice that I imported the useUpdateHeadcount file from a folder called composables.
That's because these functions to separate out logic by shared concerns are known as composables in the Vue 3 world.
Vue2 Options-based API Vue Composition API beforeCreate setup() created setup() beforeMount onBeforeMount mounted onMounted beforeUpdate onBeforeUpdate updated onUpdated beforeDestroy onBeforeUnmount destroyed onUnmounted errorCaptured onErrorCaptured
I'm not going to go over all the details of how I wrote the composable and brought it back into the component file because I'll be doing a later blog post in the series about composables.
In fact, I don't even have to use a composable; I can just write all my logic in the setup function since it's a very simple component.
But I wanted to also make it clear that as the component gets more complicated, there is a strategy for organizing the logic, and it's one of Vue 3's most exciting features.
watch is basically the same in Vue 3, so I am happy to know that I can use it as I have before. In my example, I want to track the value of numEmployees to make sure it doesn't go below zero, since it's not possible to have negative human beings as employees.
Here's my rendered component.
It looks the same, but I added a disclaimer that the headcount cannot go below zero. This restriction - not going below zero - will be managed by the logic in watch:. I specify which data property to track (numEmployees) as the first argument, and a callback as the second argument.
Inside the callback, I have my logic that causes the side effect.
Putting It All Together
If numEmployees reaches below zero, that side effect happens, setting the value to zero.
Example: Watch a Variable
The callback makes sure the side effect happens on the next tick following the value reaching below zero.