vue实现computed
computed 的基本用法
在 Vue 中,computed 是一种基于响应式依赖进行缓存的属性。它适用于需要根据其他数据动态计算的场景。computed 属性只有在依赖的响应式数据发生变化时才会重新计算。
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
}
}
}
computed 的 setter 和 getter
computed 属性默认只有 getter,但也可以提供 setter 以实现双向绑定功能。
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName: {
get() {
return `${this.firstName} ${this.lastName}`
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[1] || ''
}
}
}
}
computed 与 methods 的区别
computed 属性是基于它们的响应式依赖进行缓存的,只有在依赖发生变化时才会重新计算。而 methods 在每次调用时都会执行函数。
export default {
data() {
return {
counter: 0
}
},
computed: {
computedCount() {
return this.counter * 2
}
},
methods: {
methodCount() {
return this.counter * 2
}
}
}
computed 在 Composition API 中的使用
在 Vue 3 的 Composition API 中,computed 是通过 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
}
}
}
computed 的依赖追踪
computed 属性会自动追踪其依赖的响应式数据。如果依赖的数据没有变化,computed 属性会直接返回缓存的值,而不会重新计算。
export default {
data() {
return {
a: 1,
b: 2
}
},
computed: {
sum() {
return this.a + this.b
}
}
}
computed 的异步操作
虽然 computed 属性通常用于同步计算,但也可以通过返回 Promise 来处理异步操作。不过需要注意,这种情况下可能需要结合其他 API(如 async/await)来处理。

export default {
data() {
return {
userId: 1
}
},
computed: {
userData() {
return fetch(`https://api.example.com/users/${this.userId}`)
.then(response => response.json())
}
}
}






