Thoroughly understand the calculated properties, methods, and watches in Vue
Preface: when learning the Vue framework, we will all be exposed to the calculation properties, methods and listeners, but for beginners, it is easy to confuse these concepts, so we are going to write an article to thoroughly explain these three properties.
-
Calculated attribute
For beginners, it may not be clear where the calculation attributes, methods and listeners should be written. I will simply write a vue2 template here. Of course, the code is not uniform. Everyone's code format may be different, but the general specifications should be followed. I just list a common writing method here. If you are a big Vue, please ignore this.
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script type='text/javascript'> const options = { //Specify where this Vue instance needs to be mounted, or which container el:'#app', //data data() { return { count: 123 } }, //method methods: { }, //Calculation properties computed: { }, //Listener watch: { } } const vm = new Vue(options); </script>
Before learning the calculated attribute, let's understand the four words of calculated attribute. The English word calculated means calculation. Then we can think about what to calculate? Here is a simple example to help you understand
We know that expressions can be written in Vue's interpolation, such as:
<body> <div id='app'>{{books.length>0?'isOk':'notOk'}}</div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script type='text/javascript'> const options = { el:'#app', data() { return { books: ['Journey to the West','Water Margin','Romance of the Three Kingdoms','The Dream of Red Mansion'] } }, methods: { }, computed: { }, watch: { } } const vm = new Vue(options); </script> </body>
The effect displayed on the page must be isOk,Why? because books.length>0?'isOk':'notOk'The calculated value is isOk,stay Vue In the interpolation syntax of, expression is written. Here we can think about it, books.length>0?'isOk':'notOk'This expression doesn't seem to be calculating a certain value. Here, it's equivalent to calculating the value of this expression isOk This value is then rendered to the page. We can understand the word calculation this way. But there is a problem. What if we need to use this calculation process in many places on our page? Do we write this every place? Didn't we write a lot of more code, and we don't know the complexity of the expression. For example, we may use the calculated value in many places, so it's too troublesome for us to write the expression everywhere. Of course, you may feel it's not troublesome now. Is that it? What's it like to write this? I feel good. In fact, this is not the case, because in the future front-end development, the amount of code you are exposed to cannot be just me. You will write a lot of code, which will be more complex at that time.
<div id='app'> <div>{{books.length>0?'isOk':'notOk'}}</div> <p>{{books.length>0?'isOk':'notOk'}}</p> <a href="###">{{books.length>0?'isOk':'notOk'}}</a> </div>
At this point, Vue Just gave us one computed Property, we call it calculation property. It can be understood that this property is used for calculation. How do we write it? computed What does it say? Don't worry. Let me show you
<body> <div id='app'> <div>{{books.length>0?'isOk':'notOk'}}</div> <p>{{books.length>0?'isOk':'notOk'}}</p> <a href="###">{{books.length>0?'isOk':'notOk'}}</a> <div>{{myFirstComputed}}</div> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script type='text/javascript'> const options = { el:'#app', data() { return { books: ['Journey to the West','Water Margin','Romance of the Three Kingdoms','The Dream of Red Mansion'] } }, methods: { }, computed: { myFirstComputed() { return this.books.length>0?'isOk':'notOk' } }, watch: { } } const vm = new Vue(options); </script> </body>
Like this, just write the function directly in computed, and then write it in {}}.
Here's an explanation. All the functions written in computed will be mounted on the Vue instance, so we can use them directly. We print vm on the console, and the returned data contains the function we just wrote
With this computed, we can reduce a lot of code, which is equivalent to that we directly encapsulate a lot of code in one place and directly call the attribute name where it needs to be used.
At this point, I need everyone to remember that in the official Vue document, "for any complex logic containing responsive data, you should use computational properties." this sentence will be used later.
2. ### methods
The method is the same as the calculation attribute, that is, write the function in methods and call it directly where it needs to be used.
<body> <div id='app'> <div>{{books.length>0?'isOk':'notOk'}}</div> <p>{{books.length>0?'isOk':'notOk'}}</p> <a href="###">{{books.length>0?'isOk':'notOk'}}</a> <div>{{myFirstComputed}}</div> <div>{{myFirstMethod()}}</div> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script type='text/javascript'> const options = { el:'#app', data() { return { books: ['Journey to the West','Water Margin','Romance of the Three Kingdoms','The Dream of Red Mansion'] } }, methods: { myFirstMethod() { return this.books.length>0?'isOk':'notOk' } }, computed: { myFirstComputed() { return this.books.length>0?'isOk':'notOk' } }, watch: { } } const vm = new Vue(options); console.log(vm); </script> </body>
When printing vm, there is an additional function, which is a little different from the calculation attribute. You can see that the additional attribute is a function, so we should write it in the form of a function when calling.
To sum up, we find that the effect of computing attributes can be achieved by our methods, that is, the final results of the two methods are exactly the same. What's the difference between them?
The difference between computing attributes and methods: let's first think about the previous sentence, "for any complex logic containing responsive data, you should use computing attributes." why should computing attributes be used for any complex logic containing responsive data? The reason is that computing attributes are cached based on their response dependencies, Computed properties are re evaluated only when the relevant responsive dependencies change. In other words, if our data books are not changed, they will not be re evaluated and the results returned by the previously calculated properties will be called. Here is a cache, which is the value returned by the previously calculated property. But the method is not like this. The method does not have this mechanism. No matter where the method is called, it will execute this function. Therefore, the advantage of computing attributes is to reduce the consumption of resources. For example, a lot of logic needs to be processed in your calculation attributes. If you use calculation attributes, you can not execute each time (of course, when the responsive data has not changed), but if you use methods, you inadvertently do a lot of unnecessary things. Why waste the memory resources that can be solved?
-
Listener (watch)
The listener is actually listening to a certain attribute value. As long as the value changes, the listener function will be called, and the listener function name is the attribute name.
<body> <div id='app'> <div>{{books.length>0?'isOk':'notOk'}}</div> <p>{{books.length>0?'isOk':'notOk'}}</p> <a href="###">{{books.length>0?'isOk':'notOk'}}</a> <div>{{myFirstComputed}}</div> <div>{{myFirstMethod()}}</div> <input type="text" v-model="firstname"> {{fullname}} </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script type='text/javascript'> const options = { el:'#app', data() { return { books: ['Journey to the West','Water Margin','Romance of the Three Kingdoms','The Dream of Red Mansion'], firstname:'Lee', lastname:'four', fullname:'' } }, methods: { myFirstMethod() { return this.books.length>0?'isOk':'notOk' } }, computed: { myFirstComputed() { return this.books.length>0?'isOk':'notOk' } }, watch: { firstname() { this.fullname = this.firstname + this.lastname; } } } const vm = new Vue(options); console.log(vm); </script>
In this case, as long as firstname changes, the listener firstname will be called.
So what's the difference between listeners and computational properties?
Four words to sum up: each has its own advantages
For the listener example above, we can use the calculation attribute to implement it. Just write a calculation attribute and return this.firstname + this.lastname. But why write a listener? You have to add an attribute value fullname. Indeed, this shows the advantages of computing attributes. But what if I want to change the value asynchronously? For example, I want to change fullname five seconds after changing the value of firstname. How do you write the calculation attribute?
Change firstname, delay for 5 seconds, and change the value of fullname
watch: { firstname() { setTimeout(()=>{ this.fullname = this.firstname + this.lastname; },5000) } }
How to write calculation properties?
computed: { myFirstComputed() { setTimeout(()=>{ return this.books.length>0?'isOk':'notOk' },5000); } },
So? This is not allowed.
Therefore, listeners and calculated properties have their own advantages.