the landlord only needs to compare watch
with computed
:
The number of - listening objects is different:
watch
listening on only one object
computed
listening on multiple objects
- whether there is a return value
< hr >
Why should it be compared with computed
, because the implementation principle of both is the same, both through observer mode , and the feeling when using is also very similar, it is nothing more than a series of actions triggered by changes in the listening data.
then the applicable scenario of watch comes out naturally
requires extra action on single object changes and does not need to return
value
what if there are two objects , of which either makes a change, and what should I do when either object changes the same action
?
< hr >
write the two objects in a object
, and then watch
this object
for example:
data(){
return {
dataWrapper:{
data1:null,
data2:null
}
}
},
watch: {
dataWrapper(){
handler(){
// do something...
},
deep: true
}
}
< hr >
or
data(){
return {
data1:null,
data2:null
}
},
computed:{
dataWrapper(){
const {data1, data2} = this
return {
data1,
data2
}
}
},
watch: {
dataWrapper(){
// do something...
}
}
data coupling between multiple watch
should be avoided as far as possible. A decoupling method is introduced above.
it is reasonable to exist. Without this demand, this API will not be produced.
come on, landlord
for example, in my current subcomponent, I need to implement a function that triggers the corresponding methods if an object in the props changes.
so what method do you need to trigger the corresponding methods at this time?
it's obvious that you need to use watch here.
so the existence of each method is based on the business scenario.
your questions are really difficult to answer. Yesterday I saw a sentence: I can't ask what the design purpose of a technology is, but what problems I have encountered and what technologies can solve my problems?
Contemporary software frameworks are basically based on the thinking category of software design patterns, so watch is obviously an observer pattern in terms of semantics and practical use. Then the observer model is originally applied to who is interested in the state of change and who "observes" it. In some cases, you do need to track the changes in the observed values, and if you really want to know the values before and after the changes, you need to use watch.
if the subject encounters the above problem, you can try watch.