I'm trying to understand the difference between the two, when using one or the other, I know there are also watchers, what is the correct use of them?
I'm trying to understand the difference between the two, when using one or the other, I know there are also watchers, what is the correct use of them?
In a Vue component we have to have things organized, for this there are some concepts / parameters to take into account and that are the way to work of a component.
Here you should save functions. All kinds of functions that handle data and functionality of the component.
Saving these functions into methods allows them to be used in other components, by inheritance or by degree of kinship.
Here you can also import methods from the store.
Here you have primitive guards. Strings, arrays, objects, etc. In the background the state of the component.
Here you have a mixture of the previous two, and enters the logic / methodology of reactive programming. These methods are functions that return data are likely to have been changed between renderings. Imagine an example:
You have an image on the component and you want to pick up the corner to make it bigger. Somewhere in the logic you will have to say what width
, height
of that image. Then you want to drag it and you will have to control the left
and top
of that image.
Now instead of having a 4 values spread in the data
, and then in the template one mixed with these values type: <img :styles=""
which is difficult to maintain; the best thing is to have a computed
for this:
computed:
styles(){
return {left: this.left, top: this.top, height: this.height, width: this.width};
}
}
and in the template it gets much cleaner with only <img :styles="styles"
.
Another very useful feature is that we can import from the store the getters going to computed
and store methods that go to the methods
of the component.
The data passed to the component. This is one of the few ways of data passing, and allows rigid typing controls. What is in data
is internal to the component and possibly to its descendants. What is in props
are data to use in the component and can not be changed directly, only via change in the state of the component or part of the application that generates this data.
Here you should save methods that should be called when the value of a property of data
or props
changes. There may be cases where it works use computed
, other watch
.
As a general rule, if there is something you need to know when you change it uses watch
; when you want to always have updated data, use computed.