watch监听ref定义的数据
<script setup>
import { ref, watch } from 'vue'
let name = ref('张三')
let age = ref(19)
// 监听一个数据
watch(name, (newValue, oldValue) => {
console.log(newValue, oldValue)
}, { immediate: true })
// 监听多个数据
watch([name, age], (newValue, oldValue) => {
console.log(newValue, oldValue)
})
</script>
<template>
<span>姓名:{{ name }}</span>
<span>年龄{{ age }}</span>
<button @click="name += '~'">修改姓名</button>
<button @click="age += 1">修改年龄</button>
</template>
immediate: true 立即监听,当监听一个数据时,初始值为undefined,监听多个数据时为空数组[]
watch监听reactive定义的数据
<script setup>
import { reactive, watch } from 'vue'
const state = reactive({
userInfo: {
name: '张三',
age: 18,
job: {
job1: {
type: '前端工程师',
salary: 20,
},
},
},
})
/**
* vue版本:3.2.31
* 1.获取不到oldValue的值
* 2.默认就能监听到子级数据,deep配置无效
*/
watch(
state,
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ deep: false }
)
// 监听reactive定义数据中的某个数据
watch(
() => state.userInfo.name,
(newValue, oldValue) => {
console.log(newValue, oldValue)
}
)
// 监听reactive定义数据中的某些数据
watch([() => state.userInfo.name, () => state.userInfo.age], (newValue, oldValue) => {
console.log(newValue, oldValue)
})
// 监听reactive定义数据中属性,即包含多层数据
/*错误写法,此时修改state.userInfo.job中的salary监听不到改变,需要开启deep
watch(
() => state.userInfo.job,
(newValue, oldValue) => {
console.log(newValue, oldValue)
}
)*/
watch(
() => state.userInfo.job,
(newValue, oldValue) => {
console.log(newValue, oldValue)
},
{ deep: true }
)
</script>
<template>
<span>姓名:{{ name }}</span>
<span>年龄{{ age }}</span>
<span>薪资{{ state.userInfo.job.job1.salary }}</span>
<button @click="name += '~'">修改姓名</button>
<button @click="age += 1">修改年龄</button>
<button @click="state.userInfo.job.job1.salary += 1">涨薪</button>
</template>
监听对象类型的时候oldValue获取不到