vue3 watch 监听多值以及深度监听用法

1.监听单个值

引入:
import {…, watch} from “vue”;
import {useRouter} from ‘vue-router’;

export default {
 setup() {
 	 const route = useRouter();
 	 //获取当前路由地址
 	 watch(
        () => route.currentRoute.value.path,
        (newVal, oldVal) => {
         console.log(newVal, oldVal);
         }
      )
 }
}

2.监听多个值
还是上面路由的例子

export default {
 setup() {
 	 const route = useRouter();
 	 //获取当前路由地址
 	 watch(
        () => [route.currentRoute.value.path,route.currentRoute.value.href],
        (newVal, oldVal) => {
        //此时返回的是数组,按下标获取对应值
         console.log(newVal[0]);
         console.log(newVal[1]);
         }
      )
 }
}

2.深度监听

export default {
 setup() {
 	 const route = useRouter();
 	 //获取当前路由地址
	 watch(()=>route, (newVal, oldVal) => {
           console.log(newVal)
           console.log( oldVal)
         },
         //深度监听
         {deep: true}
     )
 }
}

你可能感兴趣的:(vue,页面遇到的基础问题,vue.js,javascript,前端)