vue3中computed函数,watch函数,watchEffect函数

本文详细介绍了 Vue.js 中的 computed 属性和 watch 机制。讲解了 computed 的简写和完整写法,以及如何设置计算属性的读写。同时,文章探讨了 watch 函数在监视 ref 和 reactive 定义的响应式数据时的行为差异,包括如何监听单个属性和多个属性的变化,并分析了 deep 配置在不同情况下的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要引入函数api才可以使用

import {ref,reactive,computed,watch,watchEffect} from 'vue'

 computed函数

		setup(){
			//数据
			let person = reactive({
			money:18,
			num:18
			})
			//计算属性——简写(没有考虑计算属性被修改的情况)
			 person.fullName = computed(()=>{
			return person.money * person.num
			}) 

			//计算属性——完整写法(考虑读和写)
			person.fullName = computed({
				get(){
					return person.money + '-' + person.num
				},
				set(value){
					const nameArr = value.split('-')
					person.money = nameArr[0]
					person.num = nameArr[1]
				}
			})

			//返回一个对象(常用)
			return {
				person
			}
		}

watch函数

  • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。

  • 监视reactive定义的响应式数据中某个属性时:deep配置有效。

//情况一:监视ref定义的响应式数据
watch(sum,(newValue,oldValue)=>{
	console.log('sum变化了',newValue,oldValue)
},{immediate:true})

//情况二:监视多个ref定义的响应式数据
watch([sum,msg],(newValue,oldValue)=>{
	console.log('sum或msg变化了',newValue,oldValue)
}) 

/* 情况三:监视reactive定义的响应式数据
			若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
			若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 
*/
watch(person,(newValue,oldValue)=>{
	console.log('person变化了',newValue,oldValue)
},{immediate:true,deep:false}) //此处的deep配置不再奏效

//情况四:监视reactive定义的响应式数据中的某个属性
watch(()=>person.job,(newValue,oldValue)=>{
	console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true}) 

//情况五:监视reactive定义的响应式数据中的某些属性
watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
	console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true})

//特殊情况
watch(()=>person.job,(newValue,oldValue)=>{
    console.log('person的job变化了',newValue,oldValue)
},{deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值