watch与computed
376字约1分钟
2024-07-27
watch与computed的区别?
watch和computed都可以监听数据变化,实现数据的响应式更新。
1.computed计算属性
- computed适合复杂的逻辑计算场景,以及数据处理返回对象。
- computed具有缓存机制,只有当依赖的属性值发生变化时才会重新计算
2.watch侦听器
- watch是监听属性值的变化,当属性值发生变化时,会执行回调函数。
- watch比较适合在数据变化时执行异步或开销较大的操作时使用。
watch与computed的使用方法和场景
1.computed使用案例
<template>
<div>
<p>商品单价: {{ price }}</p>
<p>商品数量: {{ num }}</p>
<p>总价: {{ totalPrice }}</p>
</div>
</template>
<script lang="ts" setup >
import { computed,ref } from 'vue';
const price = ref(100);
const num = ref(2);
// 触发条件
// 函数内部的响应式变量,price或者num发生变化,会重新执行,并计算totalPrice的新值
const totalPrice = computed(() => {
// 请不要在此处作用域写异步代码
// 返回被计算出的总价
return price.value * num.value
});
</script>
2.watch使用案例
<script lang="ts">
import { ref, watch } from 'vue';
const pageNum = ref(0);
// 当前环境就是分页下标pageNum变动的适合,触发内部执行函数
// newVal最新的值,oldVal旧值
watch(pageNum, async (newVal, oldVal) => {
// 此处api() 代指异步请求代码
await api()
},{
// 初次加载,立即执行,默认是false,变动一次后执行
immediate: true,
// 深度监听
deep: true
});
</script>