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

A very detailed summary of communication between Vue components

Table of contents Preface 1. Props, $emit one-way...

MAC+PyCharm+Flask+Vue.js build system

Table of contents Configure node.js+nvm+npm npm s...

How to implement the builder pattern in Javascript

Overview The builder pattern is a relatively simp...

Detailed explanation of the correct way to open em in CSS

Why do we say “usually 1em=16px”? The default tex...

Detailed explanation of as, question mark and exclamation mark in Typescript

1. The as keyword indicates an assertion In Types...

mysql method to recursively search for all child nodes of a menu node

background There is a requirement in the project ...

Why MySQL should avoid large transactions and how to solve them

What is a big deal? Transactions that run for a l...

The submit event of the form does not respond

1. Problem description <br />When JS is use...

Prevent HTML and JSP pages from being cached and re-fetched from the web server

After the user logs out, if the back button on the...

How to manage docker through UI

Docker is being used in more and more scenarios. ...

Friendly Alternatives to Find Tool in Linux

The find command is used to search for files in a...

Functions in TypeScript

Table of contents 1. Function definition 1.1 Func...

MySQL 5.7.31 64-bit free installation version tutorial diagram

1. Download Download address: https://dev.mysql.c...

Detailed explanation of the use of the clip-path property in CSS

Use of clip-path polygon The value is composed of...