当前位置:首页 > VUE

vue实现computed

2026-01-13 04:01:34VUE

在 Vue 中实现 computed

Vue 的 computed 属性用于声明基于其他响应式数据的计算属性,它会自动缓存计算结果,仅在依赖项变化时重新计算。以下是如何在 Vue 2 和 Vue 3 中实现 computed 的示例。

Vue 2 中的 computed

在 Vue 2 中,computed 通常在组件的选项中定义:

export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`
    }
  }
}

说明:

vue实现computed

  • fullName 是一个计算属性,依赖 firstNamelastName
  • firstNamelastName 变化时,fullName 会自动更新。
  • 计算结果会被缓存,避免重复计算。

Vue 3 中的 computed

在 Vue 3 中,可以使用 setup 函数和 computed 函数实现计算属性:

import { ref, computed } from 'vue'

export default {
  setup() {
    const firstName = ref('John')
    const lastName = ref('Doe')

    const fullName = computed(() => {
      return `${firstName.value} ${lastName.value}`
    })

    return { firstName, lastName, fullName }
  }
}

说明:

vue实现computed

  • 使用 refreactive 创建响应式数据。
  • 通过 computed 函数定义计算属性,传入一个 getter 函数。
  • 计算属性同样具有缓存特性。

计算属性的 setter

如果需要设置计算属性的值,可以提供一个 setter:

computed: {
  fullName: {
    get() {
      return `${this.firstName} ${this.lastName}`
    },
    set(newValue) {
      const [first, last] = newValue.split(' ')
      this.firstName = first
      this.lastName = last
    }
  }
}

说明:

  • get 方法用于获取计算属性的值。
  • set 方法在赋值时触发,可以更新依赖的数据。

计算属性 vs 方法

计算属性和方法的区别在于缓存:

  • 计算属性:基于依赖缓存,适合性能敏感的场景。
  • 方法:每次调用都会重新计算,适合需要动态结果的场景。
methods: {
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

注意事项

  1. 避免在计算属性中执行异步操作或副作用(如修改 DOM)。
  2. 计算属性应保持纯函数特性,仅依赖响应式数据。
  3. 在 Vue 3 中,computed 返回的是一个 ref 对象,需要通过 .value 访问其值。

标签: vuecomputed
分享给朋友:

相关文章

vue实现bootstrap

vue实现bootstrap

Vue 中集成 Bootstrap 的方法 在 Vue 项目中集成 Bootstrap 可以通过以下方式实现,涵盖样式、组件和交互功能。 安装 Bootstrap 依赖 通过 npm 或 yarn…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue实现slidetoggle

vue实现slidetoggle

Vue 实现 SlideToggle 效果 SlideToggle 是一种常见的交互效果,元素以滑动方式展开或收起。以下是几种实现方法: 使用 CSS Transition 和 v-show 通过…

vue实现日历

vue实现日历

Vue 实现日历的基本方法 使用 Vue 实现日历可以通过自定义组件或借助第三方库完成。以下是两种常见实现方式: 自定义日历组件 创建基于 Vue 的日历组件需要处理日期计算和渲染逻辑。核心是生成当…

vue实现uuid

vue实现uuid

使用 uuid 库生成 UUID 在 Vue 项目中,可以使用 uuid 库来生成 UUID。安装依赖: npm install uuid 在 Vue 组件中使用: import { v4 as…

vue实现循环

vue实现循环

Vue 实现循环的方法 在 Vue 中,可以通过 v-for 指令实现循环渲染列表或对象。以下是几种常见的用法: 遍历数组 使用 v-for 遍历数组时,可以同时获取当前项和索引: <ul&…