watch 和 watchEffect 都是监听器,但在写法和使用上有所区别。
watch在监听ref和reactive类型时watch函数的写法不同。
1.1、 watch监听ref类型时:
import {ref, watch} from 'vue'
export default {
setup(){
const state = ref(0)
watch(state, (newValue, oldValue) => {
console.log(`原值为${oldValue}`)
console.log(`新值为${newValue}`)
/* 1秒后打印结果:
原值为0
新值为1
*/
})
// 1秒后将state值+1
setTimeout(() => {
state.value ++
}, 1000)
}
}
1.2 watch监听reactive类型时:
import {ref, watch} from 'vue'
export default {
setup(){
const person = reactive({age: 17,name: 'Rose'})
watch(()=>person.age, (newValue, oldValue) => {
console.log(`原值为${oldValue}`)
console.log(`新值为${newValue}`)
/* 1秒后打印结果:
原值为18
新值为19
*/
})
// 1秒后将state值+1
setTimeout(() => {
person.age ++
}, 1000)
}
}
1.3 watch还有第三个参数 是一个对象,可以进行一些配置
这样配置就不是惰性的了,首次展示也会运行。
{immeddiate:true}
1.4 watch 同时监听多个参数
import {ref,reactive,watch} from 'vue'
export default {
setup(){
const value1 = ref('0')
const value2 = ref ('1')
const person = reactive({age: 18,name: 'Rose'})
watch([value1,value2],([cur1,pre1],[cur2,pre2])=>{})
watch([()=>person.age,[()=>person.name],([cur1,pre1],[cur2,pre2])=>{})
}
}
2.1 watchEffect的用法
import {ref, watchEffect} from 'vue'
export default {
setup(){
const person = reactive({age: 17,name: 'Rose'})
const state = ref('0')
watchEffect(()=>{console.log(state.value)})
watchEffect(()=>{console.log(person.age)})
// 1秒后将state值+1
setTimeout(() => {
person.age ++
state.value++
}, 1000)
}
}
3、 vue3兼容Vue2,所有vue3 中可以使用Vue2 中watch的用法
import {ref,watchEffect} from 'vue'
export default {
setup(){
const state = ref('0')
watchEffect(()=>{console.log(state.value)})
},
watch:{
state(newVal,oldVal){
console.log(newVal,oldVal)
}
}
}
虽然vue3兼容Vue2 中watch的用法,但是steup外无法调用steup内部的函数,这里的watch并没有太大的意义
4、watch和wacthEffect的区别
- 不需要手动传入依赖
- 每次初始化时会执行一次回调函数来自动获取依赖
- 无法获取到原值,只能得到变化后的值
- watchEffect会在初始化的时候执行,watch不会