Home Web Front-end Vue.js VUE3 basic tutorial: computed using Vue.js responsive framework

VUE3 basic tutorial: computed using Vue.js responsive framework

Jun 15, 2023 pm 10:19 PM
vue computed vuejs

Vue.js is an open source JavaScript framework that adopts the MVVM (Model-View-ViewModel) pattern and aims to provide a simple and flexible way to build user interfaces. Among them, the reactive framework is one of the most important features of Vue.js, which allows developers to perform two-way binding and responsive updates of data. In Vue.js, computed is one of the important concepts. This article will introduce the basic usage and examples of computed.

1. What is computed?

Computed is a property in Vue.js, which can realize the function of dynamically calculated properties. In other words, computed can dynamically calculate a new value based on the data it depends on, and the calculated property will automatically update when the data it depends on changes. Unlike methods, computed is a computed property rather than a method.

2. The basic use of computed

The computed attribute can be defined in the following way:

new Vue({
  // ...
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})
Copy after login

In the above code, we define a computed attribute of reversedMessage, which is Calculation result based on message attribute.

Next, we will use the computed attribute in the HTML template. In order to get the value of the calculated attribute, we no longer bind the message directly, but use the computed attribute, as shown below:

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
Copy after login

In the template, we can use the difference expression {{ }} to display the calculation The value of the attribute. Since we have defined reversedMessage as a computed property, Vue.js automatically does the calculation and updates the view.

3. Computed caching mechanism

When the data on which the calculated attributes depend changes, computed will automatically recalculate and update the view. However, when the data on which the calculated attribute depends does not change, computed will remember the result of the last calculation and directly return the last value. This caching mechanism can improve application performance and efficiency.

For example, in the following code, we define a computed attribute fullName:

new Vue({
  // ...
  data: {
    firstName: 'Peter',
    lastName: 'Parker'
  },
  computed: {
    fullName: function () {
      console.log('computed')
      return this.firstName + ' ' + this.lastName
    }
  }
})
Copy after login

When we access fullName for the first time, the console will output a "computed" message. However, when we modify the value of the firstName or lastName attribute, computed will not recalculate each time, but directly returns the result of the last calculation.

4. The difference between computed and methods

Both computed and methods can be used to implement the function of dynamically calculating attributes. Their main difference lies in the caching mechanism of calculated attributes.

In the example, we define a calculated property fullName and a method getFullName:

new Vue({
  // ...
  data: {
    firstName: 'Peter',
    lastName: 'Parker'
  },
  computed: {
    fullName: function () {
      console.log('computed')
      return this.firstName + ' ' + this.lastName
    }
  },
  methods: {
    getFullName: function () {
      console.log('method')
      return this.firstName + ' ' + this.lastName
    }
  }
})
Copy after login

In the template, we can call fullName and getFullName in the following way:

<div id="example">
  <p>Computed fullName: "{{ fullName }}"</p>
  <p>Method fullName: "{{ getFullName() }}"</p>
</div>
Copy after login

We found that when calling the getFullName method, it will be recalculated every time without using the cached result. Therefore, if we need to call a method frequently, using the computed attribute can improve the performance and efficiency of the application.

5. Computed example

The following is an example of calculating the total price of a shopping cart. We assume that the data structure of the shopping cart is as follows:

new Vue({
  // ...
  data: {
    items: [
      { name: 'iPhone', price: 6999, count: 1 },
      { name: 'iPad', price: 3888, count: 2 },
      { name: 'MacBook', price: 9888, count: 1 }
    ]
  },
  computed: {
    totalPrice: function () {
      var result = 0
      for (var i = 0; i < this.items.length; i++) {
        result += this.items[i].price * this.items[i].count
      }
      return result
    }
  }
})
Copy after login

In the template, we can Use the computed attribute to display the total price of the shopping cart:

<div id="example">
  <table>
    <thead>
      <tr>
        <th>商品</th>
        <th>单价</th>
        <th>数量</th>
        <th>小计</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item, index) in items" :key="index">
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.count }}</td>
        <td>{{ item.price * item.count }}</td>
      </tr>
      <tr>
        <td colspan="3">总价:</td>
        <td>{{ totalPrice }}</td>
      </tr>
    </tbody>
  </table>
</div>
Copy after login

In the above example, we define a calculated attribute totalPrice, which depends on the price and quantity of all items in the items array. Whenever the price or quantity of any item in the array changes, Vue.js will recalculate the total price and automatically update the view.

6. Summary

In Vue.js, computed is a very powerful and important feature. It is the key to realizing dynamically calculated properties. The caching mechanism of computed properties can improve application performance and efficiency. Unlike methods, computed is a computed property rather than a method. By learning and using computed, we can build excellent Vue.js applications more conveniently and efficiently.

The above is the detailed content of VUE3 basic tutorial: computed using Vue.js responsive framework. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

See all articles