9

When reloading page, I want to get current route. Sadly route.name is undefined, router.currentRoute is RefImpl object, which has correct route with '/team' inside. router.currentRoute.value is just root '/', not '/team', as expected. Is it possible to get correct value from RefImpl?

import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'Canvas',
  components: { Ring2, Map },
  setup() {
    const router = useRouter()
    const route = useRoute()

    onMounted(() => {

      console.log(route.name) //undefined
      console.log(router.currentRoute) //RefImpl with correct value ('/team')
      console.log(router.currentRoute.value) // route is '/'
      const rawObject = {...router.currentRoute}
      console.log(rawObject) // value is '/'
      ...

Router is set up like this:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/team',
    name: 'Team',
    component: () => import('../views/Team.vue')
  },
   ...
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

2 Answers 2

25

This happens because the router hasn't yet completely resolved the initial navigation when you refresh the page, so route refers to the default (/) initially in onMounted.

Vue Router's isReady() returns a Promise that resolves when the router has completed the initial navigation, so your onMounted hook can await that Promise before trying to read route.path:

import { useRoute, useRouter } from 'vue-router'
import { onMounted } from 'vue'

export default {
  setup() {
    const route = useRoute()
    const router = useRouter()

    onMounted(async () => {
      await router.isReady() 👈
      console.log('route.path', route.path)
    })
  },
}

demo

Sign up to request clarification or add additional context in comments.

1 Comment

Worth noting, this is also the earliest you can access the router meta. This is useful if you need to, say, hide the navbar until you know if the user is logged in or not.
0

Try using the composable function useRoute :

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


setup() {
   const route = useRoute();

   const path = computed(() => route.path)
}

1 Comment

Sadly not getting result that i want, when i refresh or go to localhost:8080/team, computed value still gives me '/' as a path

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.