Several ways for vue to get the current route

The first

import { defineComponent,ref} from 'vue';
import { useRouter } from 'vue-router';

const router=useRouter
//通过实例化useRouter的router对象中,含有多个属性,其中就包含了当前路由地址,

console.log('router',router.currentRoute.value.fullPath);

the second

import { getCurrentInstance } from 'vue';

const { proxy }: any = getCurrentInstance();
console.log(proxy.$router.currentRoute.value.fullpath);

Get the current component instance through getCurrentInstance, so as to get the router through it, and then Hood's current routing address

third

import {  toRaw} from 'vue';
import { useRouter } from 'vue-router';

let router = useRouter()
console.log(toRaw(router).currentRoute.value.fullPath);

通过toRaw返回其原始对象,即将实例化的router转化为useRouter

fourth

import { watch } from 'vue';
import { useRouter } from 'vue-router';

   let router = useRouter()
   watch(router,(newValue, oldValue) => {
        console.log(newValue.currentRoute.value.fullPath);},
      { immediate: true }
    );
 //这一种写法比较麻烦,但是逻辑比较简单,通过监听获取最新的router对象,进而获取路由地址,而且在第一次的时候,就要执行监听,

Fifth

import {  ref } from 'vue';
import { useRoute } from 'vue-router';

let path=ref("")
const route=useRoute()

path.value=route.path

//这一种最为简单,推荐这种

Guess you like

Origin blog.csdn.net/qq_45662523/article/details/126773807