当前位置:首页 > VUE

computed vue 实现

2026-01-07 19:05:06VUE

computed 在 Vue 中的基本用法

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

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

fullName 会根据 firstNamelastName 的变化自动更新,且仅在依赖变化时重新计算。

computed 的缓存特性

计算属性会基于依赖的响应式数据缓存结果。只有当依赖的数据(如 firstNamelastName)变化时,computed 才会重新计算。多次访问 fullName 只会触发一次计算。

console.log(this.fullName) // 计算一次
console.log(this.fullName) // 直接返回缓存

computed 的 setter 方法

默认情况下,computed 是只读的,但可以通过定义 set 方法实现可写性。

computed vue 实现

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

调用 this.fullName = 'Jane Smith' 会触发 set 方法,更新 firstNamelastName

computed 与 methods 的区别

  • 计算属性 (computed):基于依赖缓存,适合复杂计算或频繁访问的数据。
  • 方法 (methods):每次调用都会重新执行,适合需要实时计算的场景。
methods: {
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

getFullName() 每次调用都会执行,而 computedfullName 会缓存结果。

computed vue 实现

在 Vue 3 中使用 computed

Vue 3 的 Composition API 通过 computed 函数实现计算属性。

import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => `${firstName.value} ${lastName.value}`)

fullName 会响应 firstNamelastName 的变化。

computed 的依赖追踪

计算属性会自动追踪所有在计算过程中使用的响应式数据。如果依赖的数据未被使用(如条件分支中未执行的代码),则不会触发更新。

computed: {
  example() {
    if (this.flag) {
      return this.dataA // 仅当 flag 为 true 时依赖 dataA
    }
    return this.dataB
  }
}

性能优化建议

  • 避免在 computed 中执行高开销操作(如循环或异步请求)。
  • 拆分复杂计算为多个 computed 属性,提高可读性和维护性。
  • 在 Vue 3 中,使用 computed 的缓存特性减少不必要的渲染。

标签: computedvue
分享给朋友:

相关文章

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <templat…

vue实现摘要

vue实现摘要

Vue 实现摘要的方法 在 Vue 中实现文本摘要功能通常涉及截取文本的前部分内容并添加省略号。可以通过计算属性、过滤器或自定义指令来实现。 计算属性实现 在 Vue 组件中定义一个计算属性,用于截…

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转效…

vue tag实现

vue tag实现

Vue 标签实现方法 在 Vue 中实现标签功能可以通过多种方式完成,常见场景包括动态标签生成、标签输入框、标签管理等。以下是几种典型实现方案: 动态标签列表渲染 使用 v-for 指令渲染标签…

vue实现全景

vue实现全景

Vue 实现全景效果的方法 使用 Vue 实现全景效果通常需要结合第三方库或框架,以下是几种常见的方法: 使用 Three.js 和 Vue-Three.js Three.js 是一个强大的 3D…

vue实现复选

vue实现复选

Vue 实现复选框 在 Vue 中实现复选框可以通过 v-model 指令绑定数据,同时结合 input 元素的 type="checkbox" 属性来实现。以下是几种常见的实现方式: 单个复选框…