如何在页面刷新时在 onMounted 中获取当前路由?

How do I get current route in onMounted on page refresh?

重新加载页面时,我想获取当前路线。可悲的是 route.nameundefinedrouter.currentRouteRefImpl 对象,它有正确的路线,里面有 '/team'router.currentRoute.value 只是根 '/',而不是预期的 '/team'。是否可以从 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 '/'
      ...

路由器设置如下:

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

尝试使用可组合函数 useRoute :

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


setup() {
   const route = useRoute();

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

出现这种情况是因为刷新页面时路由器还没有完全解析初始导航,所以route指的是初始在onMounted中的默认值(/)。

Vue Router 的 isReady() returns 一个 Promise 在路由器完成初始导航时解析,所以你的 onMounted 钩子可以 await Promise 在尝试阅读 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