vue3 watchEffect 函数

watch 的套路是:既要指明监视的属性,也要指明监视的回调

watchEffect的套路是:不用指明监视的那个属性,监视的回调中,用到哪个属性,那就监视哪个属性。

watchEffect有点像computed:
但computed注重的是计算出来的值(回调函数的返回值),所以必须要写返回值;
而watchEffect 更注重的是过程(回调函数的函数体),所以不用写返回值。

import {ref, reactive, watchEffect} from ‘vue’

setup(){
	let sum  = ref(0)
	let mag = ref('hhhhh')
	let person = reactive({
		name:"lisi",
		age: 20,
		job:{
			job1:{
				salary:20
			}
		}
	})

	// 用到了谁就监听谁
	watchEffect (()=>{
		const x1 = sum.value
		const x2 = person.job.job1.salary
		console.log(''watchEffect 配置的回调执行了, 默认开启了immdiate:true', x1, x2)
	})
	return { sum,mag, person
		
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lzfengquan/article/details/125273467