watch 和 watchEffect的区别
watch(参数1,参数2)
参数1: 值,函数,数组
watch(要监听的数据, 回调(前后值){})
watch(依赖, 回调)
如果这个值变了,则回调会执行 ===> 回调函数{依赖}这个数据
watch(num, ()=>{ console.log("watch",num.value)})
watchEffect(回调()=>{})
- 自动执行一次回调。这个过程中,收集依赖项。
- 随后,当依赖项变化,回调也会执行
watchEffect(()=>{
// let a = num.value
console.log('watchEffect',num.value, m.value)
})
watchEffect是一种更加特殊的watch
- 它不关心前后值
- 它会自己执行一次,并自动收集依赖
- 依赖项变化,就正常执行回调
例子:
<script setup lang='ts'>
import { ref, watch, watchEffect } from 'vue';
// 初始为0
const num = ref(0)
const m = ref(0)
// watch(num, ()=>{ console.log("watch",num.value)})
watchEffect(()=>{
// let a = num.value
console.log('watchEffect',num.value, m.value)
})
// setInterval(() => {
// num.value++
// // console.log(num.value)
// }, 2000)
</script>
<template>
<div>
</div>
</template>
<style lang='less' scoped>
</style>