computed
Computing properties is mainly done for a variable logic operation, get a new value, compared with the template in the templates to write logic operation is more clear, and more conducive to later period maintenance, moreover, are computed properties by caching mechanism, when its dependence on the value of the attribute change, calculate attribute will recount. Conversely, the property value in the cache is used.
1. Basic getters
- For example, a person’s first and last name
FirstName and lastName
Next, calculate its propertiesfullName
export default {
name: "Test". data(){
return{
firstName:' '. lastName:' '. } }, computed: { fullName(){ return `The ${this.firstName} The ${this.lastName}`; } } } Copy the code
- This is actually just an abbreviation, but this is the way he actually wrote it, and this is basically a calculation of properties
getter
function
computed:{
fullName: { get() { return `The ${this.firstName} The ${this.lastName}`;
}
} } Copy the code
2. Basic setter functions
- As you can see, the full name format above is separated by a space between the names. If we set the full name, we can use the callback to return the first and last names
setter
Functions, or operationsthis.fullName='jack demon'
, the first and last names will trigger the corresponding updates.
computed:{
fullName: { get() { return `The ${this.firstName} The ${this.lastName}`;
},
set(newValue){ let names=newValue.split(' '); this.firstName=names[0]; this.lastName=names[1]; } } } Copy the code
3. Use computed attributes in combination with V-for to improve performance
- There is a saying in vUE performance improvement, yes
v-for
andv-if
It is best not to use at the same time, can reduce performance, because first you have to understand a bit, v – for higher priority than v – if, so, for example, when you have a length of 5 array need to traverse, but only more than 50 shows that after v – if only shows that even though you only show one, but still need to traverse the entire array, so, In this case, you can first filter with the computed properties and then render the list after the computed properties are filtered with v-for.Tips:
For long lists that do not need to be changed, useObject.freeze()
For performance optimization
<template>
<div>
<ul>
<li v-for="(item,index) in filterList" :key="index">{{item}}</li>
</ul> </div> </template> <script> export default { name: "Test". data(){ return{ list: [8.20.28.52.33]. } }, computed: { filterList: { get() { return this.list.filter(x= >x>50); / / [52] }, } }, } </script> Copy the code
This article was typeset using MDNICE