Menu Close

vue3 监听器 watch

一、监听基础类型

const nums = ref(9)
watch(nums, (newValue, oldValue) => {
    console.log('watch 触发', newValue)
})

二、监听复杂类型

const demo = reactive({
	name: '小郭',
	nickName: '五彩',
	soulmate: {
		name: '',
		nickName: ''
	}
})
// 监听整个对象
watch(demo, (newValue, oldValue) => {
    console.log('watch 触发', newValue)
})
//监听对象中的某个属性
watch(() => demo.name, (newValue, oldValue) => {
    console.log('watch 触发', newValue)
})
//只监听对象的子属性
watch(() => ({ ...demo }), (newValue, oldValue) => {
    console.log('watch 触发', newValue)
})
//监听对象的所有属性
watch(() => demo, (newValue, oldValue) => {
	console.log('watch 触发', newValue)
}, { deep: true })

三、组合监听

const demo = reactive({
	name: '小郭',
	nickName: '五彩',
	soulmate: {
		name: '',
		nickName: ''
	}
})
const age = ref(18)
watch([() => demo.name, age], ([newName, newNums], [oldName, oldNums]) => {
	console.log('watch 已触发: name', newName)
	console.log('watch 已触发: age', newage)
})

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注