Summary of knowledge points on using calculated properties in Vue

Summary of knowledge points on using calculated properties in Vue

Computed properties

Sometimes we put too much logic in templates, which makes the templates too heavy and difficult to maintain. For example:

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

In this case, we have to look at it for a while before we realize that we want to display the reverse string of the variable message. Moreover, it will be more troublesome once we want to use the reverse string multiple times in the template. Therefore, when we deal with complex logic, we should use calculated properties.

Basic usage

Computed properties are properties in the Vue configuration object and are used as follows:

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

For example, if we want to get the reverse string of a string, we can use the calculated property to do it:

<div id="app">
  <p>Original string: "{{ msg }}"</p>
  <p>Reverse characters: "{{ 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.

Computed properties vs methods

In fact, the functions mentioned above can also be achieved using methods such as:

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

Although the same effect can be achieved by calling methods in expressions, there is a fundamental difference between using computed properties and using methods. When using methods, each time the page is re-rendered, the corresponding method will be re-executed once, 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('Method 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 "Method executed" is printed in the console, indicating that the reversedMsg function has been executed. However, we do not need this method to be executed because the changed data has nothing to do with this function. If the logic in this function is very complex, it will also be a consumption for performance.

However, if we use calculated properties, this phenomenon will not occur, such as:

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

At this point you can see that when the data name is reassigned, the calculated property is not executed. Therefore, the most essential difference between calculated properties and methods is that calculated properties are cached based on responsive dependencies. The value of the calculated property is always stored in the cache. As long as the data it depends on does not change, each access to the calculated property will immediately return the cached result instead of executing the function again. The method will always execute the function again every time a re-rendering is triggered.

So, why do we need caching?

Suppose, we have a computed property A that requires traversing a huge array and doing huge calculations. Then we need to use this calculated property A. If there is no cache, we will execute the function of A again, so the performance overhead becomes very large.

Diving into calculated properties

In addition to being written as a function, a calculated property can also be written as an object with two properties, getter & setter. Both properties are functions. The writing 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 property as a function, which is the getter function. That is, computed properties have only getters by default. The getter's this is automatically bound to the Vue instance.

When to execute?

When we get a calculated property, the get function is executed.

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 computed property is reassigned. Parameter: The value to be reset. The this of the setter is automatically bound to the 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 a computed property, it will not change. To repeat, the computed property will only be recalculated when the dependent responsive properties change.

Exercise_Name Filter

personArr: [
  { 
    name: '', 
    src: '.jpg', 
    des: 'bad cervical vertebra', 
    sex: 'm', 
    id: '056482'
  },
  { 
    name: '', 
    src: '.jpg', 
    des: 'Who am I', 
    sex: 'f', 
    id: '157894'
  },
  { 
    name: '', 
    src: '.jpg', des: 'I am very good looking', 
    sex: 'f', 
    id: '2849245'
  },
  { 
    name: '', 
    src: '.jpeg', 
    des: 'You haven't 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,
  },
]

Knowledge point expansion:

Instance Scaling

<div id="app1"></div>

    <div id="app2">
        {
<!-- -->{reverseMes}}
    </div>
let vm1 = new Vue({
            el:'#app1',
            data:{
                mes:'hello'
            }
        })

        let vm2 = new Vue({
            el:'#app2',
            computed: {
                reverseMes(){
                    // Use the mes in the data center of the instance vm1 to reverse the string return vm1.mes.split('').reverse().join('')
                }
            }
        })

The data in the instance vm1 and vm2 can also be used to calculate the properties

In addition to being used in interpolation expressions, custom computed properties can also be used in v-bind: attribute binding to perform some style changes, etc.

The above is a detailed summary of the knowledge points of using calculated properties in Vue. For more information on how to use calculated properties in Vue, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Vue uses calculated properties to complete the production of dynamic sliders
  • Introduction to Computed Properties in Vue
  • Detailed explanation of Vue's calculated properties
  • Vue computed properties

<<:  Sample code for implementing water drop ripple animation button effect with CSS+JS

>>:  Detailed explanation of the solution to duplicate insertion of MySQL primary key and unique key

Recommend

Using js to achieve waterfall effect

This article example shares the specific code of ...

How to change password and set password complexity policy in Ubuntu

1. Change password 1. Modify the password of ordi...

Test and solution for MySQL's large memory usage and high CPU usage

After the changes: innodb_buffer_pool_size=576M -...

Two ways to start Linux boot service

Table of contents rc.local method chkconfig metho...

MySQL table return causes index invalidation case explanation

Introduction When the MySQL InnoDB engine queries...

Introduction to possible problems after installing Tomcat

1. Tomcat service is not open Enter localhost:808...

Analysis of the principle of centering elements with CSS

It is a very common requirement to set the horizo...

MySQL 8.0.20 installation tutorial and detailed tutorial on installation issues

Original address: https://blog.csdn.net/m0_465798...

A small question about the execution order of SQL in MySQL

I encountered a sql problem at work today, about ...

Use of Linux dynamic link library

Compared with ordinary programs, dynamic link lib...

Docker uses busybox to create a base image

The first line of a Docker image starts with an i...

MySQL constraint types and examples

constraint Constraints ensure data integrity and ...

Mysql Workbench query mysql database method

Mysql Workbench is an open source database client...