vue3的CompositionAPI watchEffect/watch全部用法

1、watchEffect|

<template>
     <div>
        {{title}}
     </div>
</template>	
<script>
    export default{
         setup(){
           const title = ref(null);
           const stop = watchEffect((onInvalidate)=>{
             onInvalidate(()=>{ //清除副作用
                 //request.cancel()
                console.log("onInvalidate")
             })
              console.log(title.value)
           },{
             flush:"post". //flush  post 挂载更新之前执行   
             //flush的默认值是pre
             //flush还有个sync应该很少使用,强制同步触发  
           })
         }
         stop() /调用这个可以停止侦听
         return{
           title 
         }
    }
</script>

2.、watch侦听是惰性的相对于watchEffect,可以拿到侦听前后的值

watch(()=>info.name,(new,old)=>{
      console.log("new",'old')
})
watch([name,info],(new,old)=>{
    
})
watch(()=>{
	return {...info}
}(new,old)=>{
    console.log("new",'old')
})
watch((()=>({...info}),(newInfo,oldInfo)=>{
	console.log(newInfo,oldInfo)
}{
  deep:true//深度监听
  immediate:true //立即执行
})

//如果info是reacive类型,name是ref类型
const info= reactive({name:"axin",age:18})
const name = ref("axix");
watch(([()=>({...info}),name],[newInfo,newName],[oldInfo,oldName])=>{
		console.log(newInfo,newName,oldInfo,oldName)
})

你可能感兴趣的:(vue3,javascript,前端,vue.js)