watch
watch监听ref基本类型
在Vue3里使用watch要先import引入,而且watch里面传入两个参数:第一个是监视的属性名,第二个是回调函数。
import {ref,watch} from 'vue'
let xxx = ref(0)
watch(xxx,(newValue,oldValue)=>{
.....
})
watch 监听ref对象类型
- 监听对象地址
import {ref,watch} from 'vue'
let xxx = ref({
name:'一二',
age:12
})
watch(xxx,(newValue,oldValue)=>{
.....
})
- 监听对象属性
import {ref,watch} from 'vue'
let xxx = ref({
name:'一二',
age:12
})
watch(xxx,(newValue,oldValue)=>{
.....
},{deep:true})
watch 监听reactive对象类型
import {reactive,watch} from 'vue'
let xxx = reactive({
name:'一二',
age:12
})
watch(xxx,(newValue,oldValue)=>{
.....
})
watch监听对象属性
- 基本类型属性
import {reactive,watch} from 'vue'
let xxx = reactive({
name:'一二',
age:12
})
watch(()=>xxx.name,(newValue,oldValue)=>{
.....
})
- 对象类型属性
import {reactive,watch} from 'vue'
let xxx = reactive({
name:'一二',
age:12,
car:{
color:red
}
})
watch(()=>xxx.car,(newValue,oldValue)=>{
.....
})
watch监听多个数据
import {reactive,watch} from 'vue'
let xxx = reactive({
name:'一二',
age:12,
car:{
color:red
}
})
watch([()=>xxx.name,xxx.car],(newValue,oldValue)=>{
.....
})
解除watch监听
import {ref,watch} from 'vue'
let xx = ref(0)
const stopWatch = watch(xx,(newValue,oldValue)=>{
if(true){ // 具体的设置某个条件
stopWatch()
}
})
watchEffect
watchEffect基本使用
watchEffect 接收两个参数:
- 监听回调函数,必传参数, 依赖发生变化执行, 默认初始执行
- 监听的配置对象
watchEffect(()=>{.....})
watch与watchEffect的区别
watch会明确监听某一个响应数据,而watchEffect则是隐式的监听回调函数中响应数据。watch在响应数据初始化时是不会执行回调函数的,除非配置了immediate:true。watchEffect在响应数据初始化时就会立即执行回调函数。