属性监听

  • 源对象是一个ref的属性值及其衍生式

  • 当监听的属性值发生变化时会触发监听函数执行响应的操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    const x = ref(0)
    const y = ref(0)

    // 单个 ref
    watch(x, (newX) => {
    console.log(`x is ${newX}`)
    })

    // getter 函数
    watch(
    () => x.value + y.value,
    (sum) => {
    console.log(`sum of x + y is: ${sum}`)
    }
    )

    // 多个来源组成的数组
    watch([x, () => y.value], ([newX, newY]) => {
    console.log(`x is ${newX} and y is ${newY}`)
    })

对象监听

1.对象的全部属性

  • 源对象是一个ref的对象值
  • 浅层监听:对ref对象内的属性进行更改时不会触发监听
  • 深层监听:当ref对象内任一属性发生更改时都会触发,但是性能开销更大
1
2
3
4
const user = ref({})
watch(user, (newVal, oldVal) => {
//行为
},(deep:true)//开启深度监听

2.对象的单个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const searchEmp = ref({
name: '',
gender: '',
date: [],
begin: '',
end: ''
})

//侦听searchEmp中的date属性
watch(
//这里需要用一个对象属性的getter方法,禁止属性值直接传入
() => searchEmp.value.date,
(newValue, oldValue) => {
if(newValue.length == 2){
searchEmp.value.begin = newValue[0]
searchEmp.value.end = newValue[1]
}else {
searchEmp.value.begin = ''
searchEmp.value.end = ''
}
}
)