computed 和 watch 的区别

117 阅读2分钟

computed(计算属性)

1 支持缓存,只有依赖数据发生改变,才会重新进行计算

2 计算属性具有缓存机制,只要依赖的数据不发生改变,就算函数被重复调用,计算属性也不会发生改变。

3 不支持异步,当computed内有异步操作时无效,无法[监听]数据的变化

4 在使用上:如果一个属性是由其他属性计算而来的,这个属性依赖其他属性,是一个多对一或者一对一,一般用computed

5 如果computed属性属性值是函数,那么默认会走get方法;函数的返回值就是属性的属性值;在computed中的,属性都有一个get和一个set方法,当数据变化时,调用set方法

<script setup>
import { computed, ref } from "vue";

const student = ref({ username: "涂俊俊", monthMoney: 14 });

const resstu = computed({
  get() {
    return student.value.monthMoney * 14;
  },
  set(val) {
    return (student.value.monthMoney = val / 14);
  },
});
</script>
<template>

  年薪:{{ res }}

  {{ student.username }}想要月薪{{ student.monthMoney }}k
  <input v-model="resstu" />
</template>

watch( 侦听属性)

1 不支持缓存,数据变,直接会触发相应的操作;
2 watch支持异步
3 监听的函数接收两个参数,第一个参数是最新的值;第二个参数是输入之前的值;
4 当一个属性发生变化时,需要执行对应的操作;一对多;
5 watch只会监听数据的值是否发生改变,而不会去监听数据的地址是否发生改变,要深度监听需要配合deep:true属性使用;
6 immediate:true 页面首次加载的时候做一次监听

<script setup>
import { reactive, ref, watch } from "vue";

const stu = reactive({ name: "解解", age: 18 });
const addage = ()=>{
  stu.age = 19
}
watch(
  () => stu.age,
  (newvalue, oldvalue) => {
    console.log("stu", newvalue,oldvalue);
  },{deep:true,immediate:true}
);
</script>

<template>
{{ stu.name }}今年{{ stu.age }}岁
<button @click="addage">明年他几岁了</button>
</template>

总结:

 1、 功能上:computed是计算属性,watch是侦听属性。

 2、 computed支持缓存,watch不支持缓存。

 3、 computed不支持异步,watch支持异步

 4、 computed中的函数必须要用return返回,watch中的函数不是必须要用return。

 5、 使用场景:computed----当一个属性受多个属性影响的时候,使用computed。

watch----当一条数据影响多条数据的时候,使用watch-------搜索框。