Home > Web Front-end > Vue.js > body text

Detailed explanation of computed function in Vue3: convenient use of calculated properties

WBOY
Release: 2023-06-18 20:31:40
Original
7492 people have browsed it

Detailed explanation of the computed function in Vue3: Convenient use of calculated properties

Computed properties are a commonly used method in Vue. They are mainly used to place logical calculations in templates to facilitate data manipulation and display by developers. . In Vue3, calculated properties are still a very important function, and the computed function is more convenient to use calculated properties. This article will provide a detailed introduction and explanation of the computed function in Vue3.

What is the computed function

The computed function is a built-in function in Vue3, which is mainly used to create a calculated property. By using the computed function, we can easily create a calculated property, making the code more concise and readable. The computed function is declared functionally in the component instance, and it will be automatically updated whenever the reactive variables that the computed property depends on change.

Basic usage of computed function

To use computed function to create a calculated property, you only need to declare a functional property in the component. The following is a simple example code that uses the computed function to create a calculated property:

<template>
  <div>
    <p>原来的值:{{ multiplied }}</p>
    <p>改变后的值:{{ multipliedByTwo }}</p>
    <button @click="updateValue">更新</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 10,
    }
  },
  computed: {
    multiplied() {
      return this.value * 2
    },
    multipliedByTwo() {
      return this.multiplied * 2
    },
  },
  methods: {
    updateValue() {
      this.value = 20
    }
  }
}
</script>
Copy after login

In the above example code, we define a data attribute value to represent the original value of the calculated property. Two calculated properties are created through the computed function, namely multiplied and multipliedByTwo. Among them, multiplied depends on the value variable in the data attribute, while multipliedByTwo depends on multiplied. In this way, we can easily enable calculated properties and calculate relevant values ​​in real time.

Advanced usage of computed function

The computed function also has some advanced usage, which can better control the behavior of calculated attributes. They will be introduced one by one below.

1. Getters and Setters

The computed function can control the reading and updating of calculated properties through getters and setters. Getters are read functions for computed properties, and setters are update functions for computed properties. By default, calculated properties are read-only and cannot be changed, but through the setters function, we can directly modify the value of the calculated property to achieve the purpose of forced update.

The following is an example code of a calculated property using getters and setters:

<template>
  <div>
    <p>原来的价格:{{ price }}</p>
    <p>折扣后的价格:{{ discountedPrice }}</p>
    <button @click="applyDiscount">打折</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      originalPrice: 100,
      discountPercentage: 10
    }
  },
  computed: {
    price: {
      get() {
        return this.originalPrice
      },
      set(newPrice) {
        this.originalPrice = newPrice
      }
    },
    discountedPrice() {
      const discount = this.discountPercentage / 100
      return this.price - (this.price * discount)
    }
  },
  methods: {
    applyDiscount() {
      this.price = this.price - 10
    }
  }
}
</script>
Copy after login

In the above example code, we declare a calculated property price and define its getters and setters functions. . discountedPrice depends on price. When price changes, discountedPrice will be automatically updated. In addition, we have also defined a method applyDiscount, which can directly modify the calculated attribute price by executing this method, so that the forced update of the calculated attribute can be achieved.

2. Caching of computed properties

In Vue3, caching of computed properties is enabled by default. This means that if the dependent variables of the calculated property have not changed, the calculated property will directly return the last result instead of recalculating. This saves computing time and performance and improves code execution efficiency.

The following is a sample code for computed attribute caching:

<template>
  <div>
    <p>原来的数量:{{ count }}</p>
    <p>倍数:{{ multiplier }}</p>
    <p>计算结果:{{ computedValue }}</p>
    <button @click="updateCount">更新数量</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0,
      multiplier: 2
    }
  },
  computed: {
    computedValue() {
      console.log('计算属性执行')
      return this.count * this.multiplier
    }
  },
  methods: {
    updateCount() {
      this.count++
    }
  }
}
</script>
Copy after login

In the above sample code, we declare a computed attribute computedValue, which is used to calculate the product of count and multiplier. After the mounted life cycle, the calculated property is executed once, and the cache of the calculated property will be enabled. In the updateCount method, we trigger the recalculation of computedValue by updating the value of the count variable. At this time, you can find in the console that the calculated property will only be recalculated when the value changes.

If you do not want to enable caching of calculated attributes, you can use the ref function in the calculation function. The ref function returns a responsive object, and the calculation function is recalculated each time the object is accessed.

import Vue, { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)

    const computedValue = () => {
      console.log('计算属性执行')
      return count.value * 2
    }

    return {
      count,
      computedValue
    }
  }
}
Copy after login

Summary

The computed function is a very important function in Vue3. It provides us with a very convenient way to operate data by creating calculated properties. Through the introduction of this article, I believe that readers have a basic understanding of computed functions and have mastered some advanced usage and techniques. In the development of Vue3, mastering the use of computed functions will definitely bring huge help to our coding work.

The above is the detailed content of Detailed explanation of computed function in Vue3: convenient use of calculated properties. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!