gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:25:55 27 4
gpt4 key购买 nike

重新加载页面时,我想获取当前路线。可悲的是 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

最佳答案

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

Vue 路由器的 isReady() 返回 Promise当路由器完成初始导航时解决,所以你的 onMounted Hook jar awaitPromise在尝试阅读 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

关于javascript - 如何在页面刷新时在 onMounted 中获取当前路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70594292/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com