当前位置:首页 > VUE

computed vue 实现

2026-03-27 12:43:51VUE

computed 的基本用法

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

export default {
  data() {
    return {
      firstName: '张',
      lastName: '三'
    }
  },
  computed: {
    fullName() {
      return this.firstName + ' ' + this.lastName
    }
  }
}

getter 和 setter

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

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

计算属性缓存

计算属性会基于它们的响应式依赖进行缓存。只有在依赖发生变化时才会重新计算。

computed: {
  now() {
    return Date.now()  // 不会更新,因为不是响应式依赖
  }
}

与方法的区别

方法每次调用都会执行函数,而计算属性会缓存结果。

methods: {
  getFullName() {
    return this.firstName + ' ' + this.lastName  // 每次调用都会执行
  }
},
computed: {
  fullName() {
    return this.firstName + ' ' + this.lastName  // 依赖不变时返回缓存
  }
}

在组合式 API 中使用

Vue 3 的组合式 API 中使用 computed 需要从 vue 导入。

import { ref, computed } from 'vue'

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

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

计算属性调试

可以给计算属性添加 onTrackonTrigger 选项来调试。

const fullName = computed({
  get() {
    return firstName.value + ' ' + lastName.value
  },
  set(newValue) {
    [firstName.value, lastName.value] = newValue.split(' ')
  },
  onTrack() {
    console.log('fullName 被追踪')
  },
  onTrigger() {
    console.log('fullName 被触发')
  }
})

计算属性与侦听器

计算属性适合用于派生状态,而侦听器适合在状态变化时执行异步或开销较大的操作。

computed vue 实现

watch(fullName, (newVal, oldVal) => {
  console.log(`全名从 ${oldVal} 变为 ${newVal}`)
})

计算属性的性能优化

避免在计算属性中进行复杂的计算或循环操作。对于大型列表,考虑使用分页或虚拟滚动。

标签: computedvue
分享给朋友:

相关文章

项目基于vue实现

项目基于vue实现

基于Vue实现项目的关键方法 搭建基础环境 安装Node.js和npm/yarn,确保开发环境具备运行Vue的能力。通过Vue CLI快速初始化项目结构,选择所需配置(如Babel、Router、Vu…

用vue实现滑动输入条

用vue实现滑动输入条

使用 Vue 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue observer实现

vue observer实现

Vue Observer 实现原理 Vue 的响应式系统核心是通过 Object.defineProperty(Vue 2)或 Proxy(Vue 3)实现的 Observer 模式。以下是关键实现细…

vue 实现滑动

vue 实现滑动

Vue 实现滑动效果的方法 在Vue中实现滑动效果可以通过多种方式,以下是几种常见的方法: 使用CSS过渡和动画 通过Vue的<transition>组件结合CSS过渡或动画实现滑动效果…

vue底部实现

vue底部实现

Vue 底部实现方法 在 Vue 项目中实现底部布局可以通过多种方式完成,以下是一些常见的方法: 使用固定定位 将底部元素固定在页面底部,适用于单页应用或需要始终显示的底部栏。 <temp…

vue实现gridlayout

vue实现gridlayout

Vue 实现 Grid Layout 使用 CSS Grid 布局 CSS Grid 是一种强大的布局系统,可以直接在 Vue 组件的样式中使用。通过定义网格容器和网格项,可以快速实现复杂的布局结构。…