How to get current route in Vue 3 outside of component?

93 Views Asked by At

When I'm outside of Vue component, i.e. in a store, router.currentRoute.name is undefined:

import router from '@/router'
console.log(router.currentRoute.name) // returns "undefined"

I can't use useRouter composable either, because it doesn't work outside of components:

import { useRouter } from 'vue-router'
const router = useRouter()
console.log(router) // returns "undefined"

This has never been a problem in Vue 2, where router was created with new Router().
In Vue 3, when using router with the new createRouter(), the exported router doesn't seem to expose router.currentRoute.

3

There are 3 best solutions below

0
van_folmert On BEST ANSWER

In Vue 3 instead of

router.currentRoute.name

route name should be accessed with:

router.currentRoute.value.name
0
Nechoj On

Did you try to use createRouter?

import {createRouter, createWebHashHistory} from 'vue-router';

const routes = [
// your routes
];

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
});

console.log(router);
console.log(router.currentRoute.value.path);

export default router;

I use this sequence in a module router.js that exports the router. This router then is imported in main.js and injected into the app (myApp.use(router)). It can also be imported in other modules and used there. For example, I use it tis way for unittests.

0
apinpin On

Perhaps the current route is simply not initialized yet?

For example in the root app component:

import { useRoute } from 'vue-router'
import { watch } from 'vue'

const route = useRoute()
console.log(route.name) // -> undefined

watch(route, () => {
  console.log(route.name) // -> route.name is defined
})

In a view loaded by <router-view />:

import { useRoute } from 'vue-router'
const route = useRoute()

console.log(route.name) // -> route.name is defined

Note that to access the current route, you should use useRoute rather than useRouter (see Vue Router documentation).