SoFunction
Updated on 2025-04-06

Five ways to get the current route sample code

The first type

import { defineComponent,ref} from 'vue';
import { useRouter } from 'vue-router';
const router=useRouter
//Instantiate the router object of useRouter, there are multiple attributes, which include the current routing address.('router',);

The second type

import { getCurrentInstance } from 'vue';
const { proxy }: any = getCurrentInstance();
(proxy.$);

Get the current component instance through getCurrentInstance, thus obtaining the router through it, and then Hood's current routing address

The third type

import {  toRaw} from 'vue';
import { useRouter } from 'vue-router';
let router = useRouter()
(toRaw(router).);
passtoRawReturns its original object,The one to be instantiatedrouterConvert touseRouter

The fourth type

import { watch } from 'vue';
import { useRouter } from 'vue-router';
   let router = useRouter()
   watch(router,(newValue, oldValue) => {
        ();},
      { immediate: true }
    );
 //This is a bit troublesome,But the logic is simpler,Get the latestrouterObject,Then get the routing address,And on the first time,Execute monitoring,

The fifth type

import {  ref } from 'vue';
import { useRoute } from 'vue-router';
let path=ref("")
const route=useRoute()
=
//This is the simplest,Recommend this

Summarize

This is the end of this article about five ways to obtain the current route of vue. For more related vue to obtain the current route, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!