很多人对于computed和watch 是混淆的,实际上 这两者的用途是完全完全不一样的,没必要用长篇大论来解释
computed 用于计算产生新的数据 这个数据是缓存的
watch 是监听现有数据
<template>
<div> 总共 {
{sum}}</div>
</template>
<script>
export default {
data() {
return {
name:'zhangsan',
countA:2,
countB:8
}
},
watch: {
name(newValue, oldValue) {
console.log('watch name', newValue, oldValue)
}
},
computed: {
sum() {
// 有缓存
return this.countA + this.countB
}
},
methods: {
getSum() {
// 无缓存
return this.countA + this.countB
}
},
}
</script>
【注意】 使用computed 还可以实现对项目的优化 因为computed是有缓存的,上面的例子来说 只要countA和countB的数值没有变化 就不会每次重新计算sum的值