1. Both computed and watch can observe the data changes of the page. We sometimes tend to abuse watch when processing page data changes. And usually a better approach is to use the computed property instead of the watch callback of the command.
Here I directly quote the example from the vue official website to illustrate:
html:
We want to implement the value of the third form to be spliced together the first and second, and when the values of the first two forms change, the values of the third form are also changing.
<div > <input type="text" v-model="firstName"> <input type="text" v-model="lastName"> <input type="text" v-model="fullName"> </div>
js: use watch method to implement
new Vue({ el: '#myDiv', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { = val + ' ' + }, lastName: function (val) { = + ' ' + val } } })
js: use computed to write
new Vue({ el:"#myDiv", data:{ firstName:"Den", lastName:"wang", }, computed:{ fullName:function(){ return + " " +; } } })
It is easy to see that computerized is simpler when implementing the above effects.
2. Detailed explanation of the comouted calculation properties.
In the vue template ({{}}), you can write some simple js expressions, which is very convenient. However, if a large number of or complex expressions are used in the page to process data, it will have a great impact on the maintenance of the page. At this time, computed calculation attributes are needed to handle complex logical operations.
1. Advantages:
When data has not changed, the cache is preferred. computed The computed attribute will only change the attribute to be calculated when the relevant data changes, and when the relevant data does not change, it will read the cache. Instead of thinking about the motheds method and watch method, the function is executed every time.
and getter method: (note that you use set and get when writing in vue)
- The setter method is triggered when setting the value.
- The getter method is fired when getting the value.
computed:{ fullName:{ //The es6 writing method is used here set(){ alert("set"); }, get(){ alert("get"); return + " " +; }, } }
3. Watch method
Although computed properties are very suitable in most cases, in some cases we need to customize a watcher to perform asynchronous operations when the data changes. Watch is very useful at this time.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.