Do you know when to calculate attributes with Vue?

Absrtact: when we deal with complex logic, we should use computational attributes.

This article is shared from Huawei cloud community< Do you have an in-depth understanding of calculated attributes and know when to calculate attributes with Vue? >, author: honest man.

Calculation properties

Sometimes, we put too much logic into the template, resulting in the template being too heavy and difficult to maintain. For example:

<div id="app">
  {{ message.split('').reverse().join('') }}
</div>

In this case, we have to look for some time to realize that here is the flipped string of the variable message, and it will be more troublesome once we want to use the flipped string multiple times in the template. Therefore, when we deal with complex logic, we should use computational properties.

Basic usage

The calculated attribute is an attribute in the Vue configuration object, which is used as follows:

<div id="app">
   <!-- The value of the calculated property can be like data Like data, it is used directly --> 
  {{ someComputed }}
</div>
const vm = new Vue({
  el: '#app',
  computed: {
     // The returned value is the value of the calculated property
    someComputed () {
      return 'some values'
    }
  }
})

For example, if we want to get the flipped string of a string, we can use the calculation attribute to:

<div id="app">
  <p>Original string: "{{ msg }}"</p>
  <p>Flip the character: "{{ reversedMsg }}"</p>
</div>
const vm = new Vue({
  el: '#app',
  data: {
    msg: 'Hello'
  },
  computed: {
    reversedMsg: function () {
      return this.msg.split('').reverse().join('');
    }
  }
})

We can see that the value of reversedMsg depends on the value of msg, so when we change the value of msg, the value of reversedMsg will also change.

Calculate attribute vs method

In fact, the above functions can also be realized by using methods, such as:

<div id="app">
  <p>Original string: "{{ msg }}"</p>
  <p>Flip string: "{{ reversedMsg() }}"</p>
</div>
const vm = new Vue({
  el: '#app',
  data: {
    msg: 'Hello'
  },
  methods: {
    reversedMsg: function () {
      return this.msg.split('').reverse().join('');
    }
  }
})

Although calling the same method in an expression can achieve the same effect, there are essential differences between the use of computing properties and the use of methods. When using the method, each time the page is re rendered, the corresponding method will be re executed, such as:

<div id="app">
  <p>{{ name }}</p>
  <p>{{ reversedMsg() }}</p>
</div>
const vm = new Vue({
  el: '#app',
  data: {
    msg: 'Hello',
    name: 'shanshan'
  },
  methods: {
    reversedMsg: function () {
      console.log('The method is executed');
      return this.msg.split('').reverse().join('');
    }
  }
})
vm.name = 'duyi';  

In the above example, we can see that once the value of name is changed, the page will be re rendered. At this moment, the string of method execution is printed on the console, which means that the function reversedMsg is executed, but we don't need the method execution, because the changed data has nothing to do with the function. If the logic in the function is very complex, It is also a consumption for performance.

However, if the calculation attribute is used, there will be no such phenomenon, such as:

const vm = new Vue({
  el: '#app',
  data: {
    msg: 'Hello',
    name: 'shanshan'
  },
  computed: {
    reversedMsg: function () {
      console.log('The calculation is executed');
      return this.msg.split('').reverse().join('');
    }
  }
})
vm.name = 'duyi';  

At this time, it can be seen that when the data name is re assigned, the calculation attribute is not executed. Therefore, the most essential difference between calculation attributes and methods is that calculation attributes are cached based on responsive dependencies. The value of calculation attributes is always stored in the cache. As long as the data it depends on does not change, each time the calculation attributes are accessed, the cached results will be returned immediately instead of executing the function again. The rule is that every time you trigger a re rendering, the calling method will always execute the function again.

So why cache?

Let's say that we have a calculation attribute a, which needs to traverse a huge array and do huge calculations. Then we need to use the calculation attribute A. if there is no cache, we will execute the function of a again, so the performance overhead becomes very large.

Drill down properties

In addition to being written as a function, the calculated property can also be written as an object. There are two properties in the object, getter & setter. Both properties are functions. The writing method is as follows:

const vm = new Vue({
  el: '#app',
  computed: {
    fullName: {
      getter () {
         // Some code
      },
      setter () {
         // Some code
      }
    }
  }
})

getter read

Earlier, we directly wrote the calculated attribute as a function, which is the getter function. That is to say, only getters are available by default for calculation properties. this of getter is automatically bound as Vue instance.

When?

When we get a calculated property, we execute the get function.

const vm = new Vue({
  el: '#app',
  data: {
    msg: 'Hello'
  },
  computed: {
    reversedMsg: {
      getter () {
        return this.msg.split('').reverse().join('');
      }
    }
  }
})

setter settings

Optional, the set function is executed when the calculated attribute is re assigned. Parameter: the value to be reset. this of the setter is automatically bound as a Vue instance.

const vm = new Vue({
  el: '#app',
  data: {
    msg: 'Hello',
    firstStr: ''
  },
  computed: {
    reversedMsg: {
      getter () {
        return this.msg.split('').reverse().join('');
      },
      setter (newVal) {
        this.firstStr = newVal[0];
      }
    }
  }
})

Note that even if a value is assigned to the calculation attribute, the calculation attribute will not change. After repeating, the calculation attribute will be recalculated only when the dependent responsive attribute changes.

Practice_ Name filtering

personArr: [
  { 
    name: '', 
    src: '.jpg', 
    des: 'Poor cervical spine', 
    sex: 'm', 
    id: '056482' 
  },
  { 
    name: '', 
    src: '.jpg', 
    des: 'Who am I?', 
    sex: 'f', 
    id: '157894' 
  },
  { 
    name: '', 
    src: '.jpg', des: 'I look good', 
    sex: 'f', 
    id: '2849245' 
  },
  { 
    name: '', 
    src: '.jpeg', 
    des: 'You've never seen a strange face', 
    sex: 'm', 
    id: '348515' 
  },
  { 
    name: '', 
    src: '.jpeg', 
    des: 'Guapi Liu', 
    sex: 'm', 
    id: '478454'
  }
],

Practice_ Select all products

courseList: [
  {
    poster: '.jpg',
    title: '',
    price: 1299,
    cart: 1,
    id: 0
  },
  {
    poster: '.jpg',
    title: '',
    price: 1148,
    cart: 1,
    id: 1595402664708
  },
  {
    poster: '.jpg',
    title: '',
    price: 1,
    cart: 1,
    id: 1596305473062
  },
  {
    poster: '.jpg',
    title: '',
    price: 1,
    cart: 1,
    id: 1595413512182
  },
  {
    poster: '.jpg',
    title: '',
    price: 12798,
    cart: 1,
    id: 1596302161181
  },
  {
    poster: '.jpg',
    title: '',
    price: 1,
    cart: 1,
    id: 1596300025301,
  },
]

 

Click focus to learn about Huawei cloud's new technologies for the first time~

Keywords: Vue string

Added by everisk on Wed, 01 Dec 2021 08:24:08 +0200