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).
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 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:. 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.