Vue Computed Attribute computed

  • 2021-11-29 23:08:53
  • OfStack

Catalog 1, Basic Examples 2. vs method for calculating attribute cache 3. setter for calculating attributes

Foreword:

1 In general, attributes are placed in data However, some attributes may need to go through some logical calculations before they can be obtained, so we can turn such attributes into computed attributes.

For example, the following:


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


In this place, templates are no longer simple declarative logic. You have to look at it for a while to realize that this is the variable you want to display message Gets or sets the flipped string of the. When you want to include this flip string in multiple places in the template, it will be more difficult to handle.

Therefore, for any complex logic, you should use computed attributes.

1. Basic examples


<div id="app">
  <h2> Total price: {{totalPrice}}</h2>
</div>
<script>
  const vm = new Vue({
    el: "#app",
    data: {
      message: "hello",
      books: [
        {name: '3 Romance of the Kingdom ', price: 30},
        {name: ' Dream of Red Mansions ', price: 40},
        {name: ' Journey to the West ', price: 50},
        {name: ' Outlaws of the Marsh ', price: 60},
      ],
    },
    computed: {
      //  Object of the computed property  getter
      totalPrice: function (){
          let result = 0;
          // `this`  Point  vm  Instances 
          for (let book of this.books){
            result += book.price;
          }
          return result
      }
    }
  })
</script>


Result: Total price: 180

Here we declare a computed attribute totalPrice . Then the total price of the book is calculated through for loop, and attributes like this need to be calculated are written in computed Medium.

Attribute 1 is generally available get And set Two methods, get Gets the property value, set Set the property value, computed The default in is get Property, our message 0 Is dependent on books.price If the price of the book changes, calculate the attribute totalPrice It also changes dynamically

2. vs method for calculating attribute cache

You may have noticed that we can achieve the same effect by calling methods in expressions:


<div id="app">
  <h2> Total price: {{getAllPrice()}}</h2>
</div>
<script>
  const vm = new Vue({
    el: "#app",
    data: {
      message: "hello",
      books: [
        {name: '3 Romance of the Kingdom ', price: 30},
        {name: ' Dream of Red Mansions ', price: 40},
        {name: ' Journey to the West ', price: 50},
        {name: ' Outlaws of the Marsh ', price: 60},
      ],
    },
    methods: {
      getAllPrice: function () {
        let result = 0;
        // `this`  Point  vm  Instances 
        for (let book of this.books){
          result += book.price;
        }
        return result
      }
    },
  })
</script>

We can define the same 1 function as a method instead of a calculated property. The final result of the two methods is exactly the same. However, the difference is that computed attributes are cached based on their responsive dependencies. They are re-evaluated only when the related responsive dependencies change. This means that as long as books Haven't changed yet, multiple visits totalPrice The evaluated property immediately returns the previous evaluation results without having to execute the function again.

So computed attributes are cached

Why do we need caching? Suppose we have a computational attribute with high performance overhead A It needs to traverse a huge array and do a lot of calculations. Then we may have other computed attributes that depend on A . Without caching, we will inevitably execute many times A Adj. getter ! If you don't want to have cache, please use method instead.

3. setter for calculating attributes

Calculated properties default to only getter But you can also provide one when you need it setter :


computed: {
  totalPrice: {
    get: function () {
      let result = 0;
      // `this`  Point  vm  Instances 
      for (let book of this.books){
        result += book.price;
      }
      return result
    },
    set: function (newValue) {
      for (let book of this.books){
        book.price += 10
      }
    }
  }
}


Here we added set Method, when running the vm.totalPrice=[...] When, setter Will be called, and then the total price of the book will change accordingly, but it will not be used in 1 case set


Related articles: