Vue computed properties

Vue computed properties

Preface:

Generally, attributes are placed in data , but some attributes may need to be obtained after some logical calculations, so we can turn such attributes into calculated attributes.

For example:

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


At this point, the template is no longer just a simple declarative logic. You have to look at it for a while to realize that what we want here is to display the reverse string of the variable message . It becomes even more difficult to handle when you want to include this flipped string in multiple places in your template.

So, for any complex logic, you should use computed properties.

1. Basic Examples

<div id="app">
  <h2>Total Price: {{totalPrice}}</h2>
</div>
<script>
  const vm = new Vue({
    el: "#app",
    data: {
      message: "hello",
      books:
        {name: 'Romance of the Three Kingdoms', price: 30},
        {name: 'Dream of Red Mansions', price: 40},
        {name: 'Journey to the West', price: 50},
        {name: 'Water Margin', price: 60},
      ],
    },
    computed: {
      // Computed property getter
      totalPrice: function (){
          let result = 0;
          // `this` refers to the vm instance for (let book of this.books) {
            result += book.price;
          }
          return result
      }
    }
  })
</script>


Result: Total price: 180

Here we declare a computed property totalPrice . Then the total price of the book is calculated through a for loop. Attributes that need to be calculated are written in computed .

Attributes generally have two methods: get and set . get gets the attribute value, and set sets the attribute value. The default in computed is get attribute. Our vm.totalPrice depends on books.price . If the price of the book changes, the calculated attribute totalPrice will also change dynamically.

2. Computed property cache vs method

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: 'Romance of the Three Kingdoms', price: 30},
        {name: 'Dream of Red Mansions', price: 40},
        {name: 'Journey to the West', price: 50},
        {name: 'Water Margin', price: 60},
      ],
    },
    methods: {
      getAllPrice: function () {
        let result = 0;
        // `this` refers to the vm instance for (let book of this.books) {
          result += book.price;
        }
        return result
      }
    },
  })
</script>

We can define the same function as a method instead of a computed property. The end result is indeed exactly the same either way. However, the difference is that computed properties are cached based on their reactive dependencies. They are only re-evaluated when the associated reactive dependencies change. This means that as long as books has not changed, accessing totalPrice computed property multiple times will immediately return the previously calculated result without having to execute the function again.

So the calculated properties are cached

Why do we need caching? Suppose we have a computationally expensive property A that requires traversing a huge array and doing a lot of calculations. We may then have other computed properties that depend on A Without caching, we would inevitably execute A 's getter multiple times! If you don't want caching, use methods instead.

3. Computed property setters

Computed properties have only getter by default, but you can also provide a setter if needed:

computed: {
  totalPrice:
    get: function () {
      let result = 0;
      // `this` refers to the vm instance 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 have added a set method. When running vm.totalPrice=[...] , setter will be called and the total price of the book will change accordingly. However, set is not usually used.

This is the end of this article about Vue computed properties. For more related Vue computed content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue calculated property implementation transcript
  • A brief talk about calculated properties and property listening in Vue
  • Introduction to Computed Properties in Vue
  • Vue uses calculated properties to complete the production of dynamic sliders
  • Vue monitoring properties and calculated properties
  • Computed properties and data acquisition methods in Vue
  • Do you know Vue's computed properties?
  • Three implementation methods of Vue's calculated property name case

<<:  Explanation of the concept and usage of Like in MySQL

>>:  Discussion on the way to open website hyperlinks

Recommend

Detailed explanation of data types in JavaScript basics

Table of contents 1. Data Type 1.1 Why do we need...

Learn Vue middleware pipeline in one article

Often when building a SPA, you will need to prote...

A detailed summary of HTML tag nesting rules suitable for beginners

I have been relearning HTML recently, which can be...

Two usages of iFrame tags in HTML

I have been working on a project recently - Budou...

Detailed explanation of Javascript basics loop

Table of contents cycle for for-in for-of while d...

Example of how to set automatic creation time and modification time in mysql

This article describes how to set the automatic c...

Analysis of the configuration process of installing mariadb based on docker

1. Installation Search the mariadb version to be ...

Where is mysql data stored?

MySQL database storage location: 1. If MySQL uses...

Mysql 5.6.37 winx64 installation dual version mysql notes

If MySQL version 5.0 already exists on the machin...

MySQL encryption and decryption examples

MySQL encryption and decryption examples Data enc...

Summary of common tool functions necessary for front-end development

1. Time formatting and other methods It is recomm...

XHTML Getting Started Tutorial: XHTML Web Page Image Application

<br />Adding pictures reasonably can make a ...

display:grid in CSS3, an introduction to grid layout

1. Grid layout (grid): It divides the web page in...