Features, usage scenarios and examples of vue computed

In Vue, computed is a computed attribute that is used to calculate based on existing data attributes and return a new attribute value. The computed attribute has the following characteristics:

features

cache

The calculation results of computed will be cached, and will be recalculated only when the dependent data changes. This caching mechanism can improve performance and avoid unnecessary calculations.

Responsiveness

When the dependent data changes, the computed attribute will be automatically recalculated, and when the dependent data has not changed, the computed attribute will directly return the previously cached result.

Declarative

The definition of computed attribute is similar to ordinary data attribute, but it is a function inside, which can process the dependent data as needed and return a new calculation result.

Usage scenarios and examples

data processing

When you need to process, convert, and format existing data, you can use the computed attribute. For example, format raw date data into a specific date string.

<template>
  <div>
    <p>{
   
   { originalData }}</p>
    <p>{
   
   { formattedData }}</p>
  </div>
</template>
<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      originalData: '2022-01-01',
    };
  },
  computed: {
      
      
    formattedData() {
      
      
      // 将原始的日期数据格式化为特定的日期字符串
      const date = new Date(this.originalData);
      return date.toLocaleDateString('en-US', {
      
       dateStyle: 'long' });
    },
  },
};
</script>

filter and sort

The computed property can be used when filtering or sorting list data is required. For example, filter out data that meets a condition based on a certain condition.

<template>
  <div>
    <ul>
      <li v-for="item in filteredList" :key="item.id">{
   
   { item.name }}</li>
    </ul>
  </div>
</template>
<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      list: [
        {
      
       id: 1, name: 'Apple', category: 'fruit' },
        {
      
       id: 2, name: 'Banana', category: 'fruit' },
        {
      
       id: 3, name: 'Carrot', category: 'vegetable' },
      ],
      filterCategory: 'fruit',
    };
  },
  computed: {
      
      
    filteredList() {
      
      
      // 根据filterCategory过滤出满足条件的数据
      return this.list.filter((item) => item.category === this.filterCategory);
    },
  },
};
</script>

dependencies

Computed properties can be used when the value of one data property depends on the values ​​of multiple other properties. For example, computing the sum or difference of two numeric attributes.

<template>
  <div>
    <p>Number 1: {
   
   { number1 }}</p>
    <p>Number 2: {
   
   { number2 }}</p>
    <p>Sum: {
   
   { sum }}</p>
  </div>
</template>
<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      number1: 5,
      number2: 10,
    };
  },
  computed: {
      
      
    sum() {
      
      
      // 计算两个数值属性的和
      return this.number1 + this.number2;
    },
  },
};
</script>

string concatenation

When multiple data attributes need to be concatenated into a string, the computed attribute can be used. For example, concatenate username and user role into a welcome statement.

<template>
  <div>
    <p>Username: {
   
   { username }}</p>
    <p>Role: {
   
   { role }}</p>
    <p>Welcome: {
   
   { welcomeMessage }}</p>
  </div>
</template>
<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      username: 'John',
      role: 'Admin',
    };
  },
  computed: {
      
      
    welcomeMessage() {
      
      
      // 将用户名和用户角色拼接成一个欢迎语句
      return `Welcome, ${ 
        this.username}! You are a ${ 
        this.role}.`;
    },
  },
};
</script>

It should be noted that the computed attribute can only be used for data calculation within the same component, and cannot be used for data transfer across components. If you need to share computed properties between different components, you can consider using Vuex or event bus to achieve it.

Guess you like

Origin blog.csdn.net/gjwgjw1111/article/details/132688288