First !! 先看原始的代码
onMounted(() => {
const currentPath = route.path
})
刷新页面 发现获取的 currentPath 始终是 /
这是 Vue Router 初始化时序问题:
- 页面刚刷新时,Vue 还没完成路由解析
onMounted执行得太早,路由还没准备好- 此时路由默认值就是
/,所以永远拿到根路径
正确的获取当前路由地址的方法
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
onMounted(async () => {
await router.isReady();
const currentPath = route.path
}
)
修改成这样, 每次获取到的路由地址就是当前页面的最新路径了.