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

Summary of basic usage of $ symbol in Linux

Linux version: CentOS 7 [root@azfdbdfsdf230lqdg1b...

A complete list of meta tag settings for mobile devices

Preface When I was studying the front end before,...

Detailed steps for setting up and configuring nis domain services on Centos8

Table of contents Introduction to NIS Network env...

MySQL kill command usage guide

KILL [CONNECTION | QUERY] processlist_id In MySQL...

JS realizes the effect of picture waterfall flow

This article shares the specific code of JS to re...

Use native js to simulate the scrolling effect of live bullet screen

Table of contents 1. Basic principles 2. Specific...

Vue implements file upload and download

This article example shares the specific code of ...

JavaScript canvas to achieve meteor effects

This article shares the specific code for JavaScr...

MySQL full-text search usage examples

Table of contents 1. Environmental Preparation 2....

Multiple ways to calculate age by birthday in MySQL

I didn't use MySQL very often before, and I w...

Solution to MySQL Installer is running in Community mode

Today I found this prompt when I was running and ...

How to build nfs service in ubuntu16.04

Introduction to NFS NFS (Network File System) is ...