Vue3中watch与watchEffect的使用

64 阅读1分钟

watch使用

监听一个数据源
let message = ref<string>("")

//监听一个数据源
watch(message,(newVal,oldVal)=>{
  console.log("新值=======>",newVal)
  console.log("旧值=======>",oldVal)
})
监听多个数据源
let message = ref<string>("")
let message2 = ref<string>("")

//监听多个数据源
watch([message,message2],(newVal,oldVal)=>{
  console.log("新值=======>",newVal)
  console.log("旧值=======>",oldVal)
})
配置项(immediate,deep)
let message3 = ref({
    hobby:{
        like:{
            name: "栗子"
        }
    }
})
//开启深度监听时,有一个问题就是新值和旧值一样
watch(message3,(newVal,oldVal)=>{
  console.log("新值=======>",newVal)
  console.log("旧值=======>",oldVal)
},{
  immediate: true,  //开启立即监听
  deep: true   //深度监听
})

注意:使用reactive监听深层对象开启和不开启deep效果一样

let message4 = reactive({
    name: "栗子",
    describe: "追光的栗子",
})
//只监听一个值(单一项)
watch(()=>message4.describe, (newVal, oldVal) => {
    console.log('新的值----', newVal);
    console.log('旧的值----', oldVal);
})

watchEffect使用

let status = ref<string>("大海")
let status1 = ref<string>("大海的贝壳")
//一进页面函数就会调用
watchEffect(() => {
    console.log('status', status.value);
    console.log('status1', status1.value);
})
清除副作用(在触发监听之前会调用一个函数来处理逻辑,例如防抖)
watchEffect((oninvalidate) => {
    oninvalidate(()=>{
        //在监听数据之前触发
    })
  console.log('status', status1.value);
})
停止监听
const stop = watchEffect((oninvalidate) => {
  console.log('status', status1.value);
})
stop()   //调用函数,停止监听
其他配置
const stop = watchEffect(() => {
  //获取页面demo元素   此时页面demo还没有加载,输出为null
  let btn: HTMLButtonElement = document.querySelector("#btn") as HTMLButtonElement
},{
    flush:"post",   //组件更新后执行(配置之后可获取页面demo元素)
    //可进行调试
    onTrigger(e){
     debugger
    }
})