首页 > 其他分享 >computed

computed

时间:2024-02-18 09:12:14浏览次数:17  
标签:Vue return computed property data 属性

Computed properties are unique data types that will reactively update only when the source data used within the property is updated. By defining a data property as a computed property, we can perform the following activities:

  • Apply custom logic on the original data property to calculate the computed property’s value
  • Track the changes of the original data property to calculate the updated value of the computed property
  • Reuse the computed property as local data anywhere within the Vue component

计算属性是一种独特的数据类型,只有在属性中使用的源数据更新时才会被动更新。通过将数据属性定义为计算属性,我们可以执行以下活动:

  • 在原始数据属性上应用自定义逻辑,计算计算属性的值

  • 跟踪原始数据属性的变化,计算计算属性的更新值

  • 在 Vue 组件中的任何位置将计算属性作为本地数据重复使用

By default, the Vue engine automatically caches the computed properties, making them more performant at updating the UI than using the property of the returned value of data, or using a Vue component’s method.

默认情况下,Vue 引擎会自动缓存计算属性,这使得它们在更新 UI 时比使用数据返回值的属性或使用 Vue 组件的方法更高效。

The syntax of a computed property is like writing a component method with a return value, nested under the computed property of the Vue component:

计算属性的语法就像编写一个带有返回值的组件方法,嵌套在 Vue 组件的计算属性下:

<script>
export default {
  computed: {
    yourComputedProperty() {
      /* need to have return value */
    }
  }
}
</script>

Within the computed property’s logic, you can access any component’s data property, method, or other computed property using the this instance, which is the reference to the Vue component instance itself. An example of using the this instance is shown here:

在计算属性的逻辑中,你可以使用 this 实例访问任何组件的数据属性、方法或其他计算属性,this 实例是对 Vue 组件实例本身的引用。下面是一个使用 this 实例的示例:

<script>
export default {
  data() {
    return {
      yourData: "your data"
    }
  },
  computed: {
    yourComputedProperty() {
      return `${this.yourData}-computed`;
    }
  }
}
</script>

Let’s look at some examples of where you should consider using a computed property.

让我们举例说明在哪些情况下应考虑使用计算属性。

表单校验

In the following example, we have an input field, which attaches to the name data property, and error is a computed property. If name contains a falsy value (which means name is an empty string, 0, undefined, null, or false), error will be assigned a value of "Name is required". Otherwise, it will be empty.

在下面的示例中,我们有一个与 name 数据属性相连的输入字段,而 error 是一个计算属性。如果 name 包含虚假值(即 name 为空字符串、0、未定义、空或 false),error 将被赋值为 "Name is required"。否则,该值将为空。

The component then renders the value of the error property accordingly:

然后,组件会相应地渲染错误属性的值:

<template>
  <input v-model="name">
  <div>
    <span>{{ error }}</span>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: '',
    }
  },
  computed: {
    error() {
      return this.name ? '' : 'Name is required'
    }
  }
}
</script>

合并数据属性

You can use computed props to combine multiple data properties to generate a single computed property. Take the following code for instance. We combine two pieces of data – title and surname – into one computed string, formalName, and render its value using template:

你可以使用计算道具来组合多个数据属性,生成一个计算属性。以下面的代码为例。我们将标题和姓氏这两个数据合并为一个计算字符串 formalName,并使用模板呈现其值:

<template>
  <div>{{ formalName }}</div>
</template>
<script>
export default {
  data() {
    return {
      title: 'Mr.',
      surname: 'Smith'
    }
  },
  computed: {
    formalName() {
      return `${this.title} ${this.surname}`;
    }
  }
}
</script>

计算和显示复杂信息

Sometimes there is a need to perform an extra calculation or to extract specific information from one large data object source. Computed properties help to achieve this goal while keeping our code readable.

有时需要执行额外的计算,或从一个大型数据对象源中提取特定信息。计算属性有助于实现这一目标,同时保持代码的可读性。

Take a large data object, such as post. This data object has a nested fields property, which contains several additional information objects, such as the full name of author and an array of entries objects. Each entry in entries contains further information, such as title, content, and a feature flag indicating whether the entry should be featured:

以一个大型数据对象为例,如 post。该数据对象有一个嵌套字段属性,其中包含多个附加信息对象,如作者全名和条目对象数组。条目中的每个条目都包含更多信息,如标题、内容和表示条目是否应被突出显示的特征标志:

<script>
export default {
  data() {
    return {
      post: {
        fields: {
          author: {
            firstName: 'John',
            lastName: 'Doe'
          },
          entries: [{
            title: "Entry 1",
            content: "Entry 1's content",
            featured: true
          },
            {
              title: "Entry 2",
              content: "Entry 2's content",
              featured: false
            }]
        }
      }
    }
  },
}
</script>

In this scenario, you need to perform the following steps:

  • Display the full name of the post’s author.
  • Calculate and display the total number of entries included.
  • Display a list of entries that have the feature flag turned on (feature: true).

在这种情况下,您需要执行以下步骤:

  • 显示帖子作者的全名。
  • 计算并显示包含的条目总数。
  • 显示已打开特征标志(特征:true)的条目列表。

By using computed properties, we can decouple the previous post object into several computed data properties while keeping the original post object unchanged, as follows.

通过使用计算属性,我们可以将之前的文章对象解耦为多个计算数据属性,同时保持原始文章对象不变,如下所示。

<script>
export default {
  data() {
    return {
      post: {
        fields: {
          author: {
            firstName: 'John',
            lastName: 'Doe'
          },
          entries: [{
            title: "Entry 1",
            content: "Entry 1's content",
            featured: true
          },
            {
              title: "Entry 2",
              content: "Entry 2's content",
              featured: false
            }]
        }
      }
    }
  },
  computed: {
    // fullName 用于合并 post.fields.author 的名和姓:
    fullName() {
      const {firstName, lastName} =
          this.post.fields.author;
      return `${firstName} ${lastName}`
    },
    // totalEntries 包含 post.fields.entries 数组的长度:
    totalEntries () {
      return this.post.fields.entries.length
    },
    // featuredEntries 包含根据每个条目的特征属性过滤后的 post.fields.entries 列表,使用的是 filter 内置数组方法:
    featuredEntries() {
      const { entries } = this.post.fields;
      return entries.filter(entry => !!entry.featured)
    }
  }
}
</script>

You then use the simplified and semantic computed properties to render the information in your component’s template.

然后,使用简化和语义计算属性在组件模板中呈现信息。

<template>
  <div>
    <p>{{ fullName }}</p>
    <p>{{ totalEntries }}</p>
    <p>{{ featuredEntries }}</p>
  </div>
</template>

Computed properties are very valuable to Vue developers when creating performant components. In the next exercise, we will explore how to use them inside a Vue component.

在创建高性能组件时,计算属性对 Vue 开发人员非常有价值。在下一个练习中,我们将探讨如何在 Vue 组件中使用它们。

练习:使用计算属性

In this exercise, you will use a computed property to help cut down the amount of code you need to write inside your Vue templates by concisely outputting basic data.

在本练习中,您将使用计算属性,通过简洁地输出基本数据,帮助减少 Vue 模板中需要编写的代码量。

Let’s create a new Vue component called Exercise2-01 by adding the Exercise2-01.vue file to the ./src/components/ folder:

让我们在 ./src/components/ 文件夹中添加 Exercise2-01.vue 文件,创建一个名为 Exercise2-01 的新 Vue 组件:

在App.vue中,引入并使用该组件:

<script setup>
import Exercise from "./components/Exercise2-01.vue";
</script>
<template>
  <Exercise/>
</template>

Open Exercise2-01.vue and let’s create the code block structure for the Vue component, as follows:

打开 Exercise2-01.vue,为 Vue 组件创建代码块结构,如下所示:

<template>
</template>
<script>
export default {
}
</script>

In <template>, create an input field for the first name, and use v-model to bind the data prop, firstName, to this field:

在 <template> 中,为名字创建一个输入字段,并使用 v-model 将数据道具 firstName 绑定到该字段:

<input v-model="firstName" placeholder="First name" />

Create a second input field for the last name, and use v-model to bind the data prop, lastName, to this field:

为姓氏创建第二个输入字段,并使用 v-model 将数据道具 lastName 与该字段绑定:

<input v-model="lastName" placeholder="Last name" />

Include these new v-model data props in the Vue instance by returning them in the data() function:

通过在 data() 函数中返回这些新的 v 模型数据道具,将其包含在 Vue 实例中:

<script>
export default {
  data() {
    return {
      firstName: '',
      lastName: '',
    }
  },
}
</script>

 

标签:Vue,return,computed,property,data,属性
From: https://www.cnblogs.com/leochan007/p/18018748

相关文章

  • 《属性篇》属性computed
    参考链接:https://www.runoob.com/vue2/vue-computed.htmlvue.js计算属性computed,计算属性在处理一些复杂逻辑时是很有用的。可以看下以下反转字符串的例子:<divid="app">{{message.split('').reverse().join('')}}</div>实例1中模板变的很复杂起来,也不容易看懂理解。......
  • vue2中 watch和computed的区别
    计算属性(Computed):computed是基于依赖关系进行缓存的。只有当相关的响应式依赖发生改变时,才会重新求值。适合于执行更复杂的数据操作。computed属性是计算出来的,不会对原始数据造成任何副作用。computed属性可以具有setter和getter方法,可以更灵活地控制数据的操作。......
  • v-for v-if不建议一起用 解决办法 使用 computed
    <el-table-columnv-for="(item,index)innewDynamicColumns":key="index":prop="item.prop":label="item.label":align="item.align":width=&qu......
  • Vue源码学习(十七):实现computed计算属性
    好家伙,本章我们尝试实现computed属性 0.完整代码已开源https://github.com/Fattiger4399/analytic-vue.git 1.分析1.1computed的常见使用方法1.计算依赖数据:当某个数据发生变化时,computed属性可以自动更新,并返回计算结果。例如:<template><div><p>用户姓名:{{u......
  • uniapp中的computed
    在UniApp中,computed是一个特殊的属性,用于计算属性。它与Vue.js中的computed属性类似,用于根据已有的数据计算出一个新的属性值。在UniApp中,使用computed属性可以方便地根据多个变量或表达式计算出一个新的变量值,并且当依赖的数据变化时,computed属性会自动更新。<template><......
  • vue中watch、computed、methods的执行顺序
    一、默认加载情况如果watch不加immediate:true属性(页面初加载的时候,不会执行watch,只有值变化后才执行),则只执行computed(在mounted后执行);如果watch添加immediate:true属性(在beforeCreate后created前执行),则先执行watch、再执行computed;二、触发某一事件后先执行method,再watch,再......
  • vue中created、watch和computed的执行顺序
    总结关于vue中created和watch的执行顺序相对比较简单,而其中computed是通过Object.defineProperty为当前vm进行定义,再到后续创建vNode阶段才去触发执行其get函数,最终执行到计算属性computed对应的逻辑。官网的生命周期图中,initreactivity是晚于beforeCreate......
  • watch和computed的其中一个关键区别就是watch可以执行异步操作,而computed不能执行异步
    下面说法错误的是()Awatch方法中不能执行异步操作B不应该使用箭头函数来定义method函数,箭头函数绑定了父级作用域的上下文,所以this将不会按照期望指向Vue实例CVue实例将会在实例化时调用$watch(),遍历watch对象的每一个propertyDcomputed的结果会被缓存,除非依赖......
  • vue计算属性computed简单使用
    computed的作用computed用data中现有的属性计算出一个新的属性,叫做计算属性,计算属性和data中属性在{{}}写法和属性一样,例如计算属性name写为<div>{{name}}</div>computed的定义位置computed的定义位置和methods还有data为同级写法为computed:{}<script>exportdefault{data()......
  • computed&watch
    computed计算属性对于任何复杂逻辑,你都应当使用计算属性。computed计算属性的作用是对数据的计算和缓存,优点是能够提高性能。vue2中,没咋用vue2写过项目,所以基本的代码展示都以vue3的格式。method:{},computed:{},vue3constnum1=ref('')constnum2=ref('')......