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

vue实现贴图

vue实现贴图

Vue 实现贴图功能 在Vue中实现贴图功能通常涉及将图片动态添加到指定位置或元素上。以下是几种常见实现方式: 使用v-bind动态绑定图片 通过数据驱动的方式动态更换图片源: <templ…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue实现录像

vue实现录像

Vue 实现录像功能 在 Vue 中实现录像功能通常需要借助浏览器的 MediaDevices API 和 MediaRecorder API。以下是实现步骤: 获取用户摄像头和麦克风权限 使用 n…

vue实现快手

vue实现快手

Vue 实现类似快手的功能 Vue.js 是一个渐进式 JavaScript 框架,适合构建复杂的单页应用。要实现类似快手的功能,可以结合 Vue 和相关技术栈进行开发。 核心功能模块 视频流展示…

vue实现ide

vue实现ide

Vue 实现 IDE 的基本思路 使用 Vue 构建一个简易的集成开发环境(IDE)需要整合代码编辑器、文件管理、终端模拟等功能。以下是关键实现步骤和推荐工具。 核心功能模块 代码编辑器 使用…