当前位置:首页 > VUE

vue computed 实现

2026-01-07 08:22:43VUE

computed 的基本用法

在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。

new Vue({
  data: {
    firstName: '张',
    lastName: '三'
  },
  computed: {
    fullName: function() {
      return this.firstName + ' ' + this.lastName
    }
  }
})

computed 的 getter 和 setter

计算属性默认只有 getter,但也可以提供 setter 方法。

vue computed 实现

computed: {
  fullName: {
    get: function() {
      return this.firstName + ' ' + this.lastName
    },
    set: function(newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

computed 与 methods 的区别

计算属性是基于它们的响应式依赖进行缓存的,只有在相关依赖发生改变时才会重新求值。相比之下,每当触发重新渲染时,methods 调用总会执行函数。

methods: {
  getFullName: function() {
    return this.firstName + ' ' + this.lastName
  }
}

computed 与 watch 的区别

watch 更适用于数据变化时执行异步或开销较大的操作。computed 更适合同步计算派生值。

vue computed 实现

watch: {
  firstName: function(val) {
    this.fullName = val + ' ' + this.lastName
  },
  lastName: function(val) {
    this.fullName = this.firstName + ' ' + val
  }
}

Vue 3 中的 computed

在 Vue 3 中,可以使用 computed 函数来创建计算属性。

import { ref, computed } from 'vue'

setup() {
  const firstName = ref('张')
  const lastName = ref('三')

  const fullName = computed(() => {
    return firstName.value + ' ' + lastName.value
  })

  return {
    fullName
  }
}

computed 的依赖追踪

计算属性会自动追踪其依赖关系,当依赖的响应式属性变化时,计算属性会自动更新。这使得计算属性非常高效,避免了不必要的重复计算。

computed 的缓存机制

计算属性的结果会被缓存,除非依赖的响应式属性发生变化,否则多次访问计算属性会立即返回缓存结果,而不会重新执行计算函数。

标签: vuecomputed
分享给朋友:

相关文章

vue实现点击页面切换

vue实现点击页面切换

实现点击页面切换功能 在Vue中实现点击页面切换功能,可以通过路由跳转或组件动态渲染两种方式完成。以下是具体实现方法: 使用Vue Router实现页面跳转 安装Vue Router后,在项目中…

vue实现截图

vue实现截图

Vue 实现截图的方法 使用 html2canvas 库 安装 html2canvas 库: npm install html2canvas 在 Vue 组件中使用: import html2…

vue 实现闪烁

vue 实现闪烁

Vue 实现闪烁效果的方法 方法一:使用 CSS 动画 在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。 <template&…

vue实现全景

vue实现全景

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

vue 实现过滤

vue 实现过滤

Vue 实现过滤的方法 在 Vue 中实现过滤功能可以通过多种方式完成,包括使用计算属性、自定义过滤器、第三方库等。以下是几种常见的实现方法: 使用计算属性进行过滤 计算属性是 Vue 中最常用的过…

vue实现选择

vue实现选择

Vue 实现选择功能的方法 在 Vue 中实现选择功能可以通过多种方式完成,以下介绍几种常见的实现方法。 使用 v-model 绑定单选 通过 v-model 可以轻松实现单选功能。以下是一个简单的…