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
CodePudding user response:
Try using the composable function useRoute :
import {
useRoute
} from 'vue-router'
import {
computed
} from 'vue'
setup() {
const route = useRoute();
const path = computed(() => route.path)
}
CodePudding user response:
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() 