侦听
# Vue3
# 侦听
# 监听一个ref
setup() {
const number = ref(0)
// 监听 number 变量,如果有发生变化,自动运行后面的回调函数(number新值,number旧值)
watch(number, (newVal, oldVal) => {
console.log({ newVal, oldVal })
})
return { number }
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 监听多个ref
import { ref, watch } from 'vue'
setup() {
const number = ref(0)
const msg = ref('你好')
// number、msg任意一个ref改变就会触发
watch([number, msg], (newVal, oldVal) => {
console.log({ newVal, oldVal })
})
return { number, msg }
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 深度侦听
想侦听state多个值的话,不如开启deep
,深度侦听后,state所有层次字段都能被侦听到。
import { ref, watch } from 'vue'
setup() {
const state = reactive({
id: 1,
attributes: {
name: '',
}
})
// 未开启deep
watch(
() => state,
(state, prevState) => {
console.log('not deep', state.attributes.name, prevState.attributes.name)
}
)
// 开启deep
watch(
() => state,
(state, prevState) => {
console.log('deep', state.attributes.name, prevState.attributes.name)
},
{ deep: true }
)
return { ...toRefs(state) }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
编辑 (opens new window)
上次更新: 2022/06/17