Vue路由器如何在页面加载时获取懒加载模块的当前路由路径?

47

我的Vue应用程序有路由设置如下:

import index from './components/index.vue';
import http404 from './components/http404.vue';

// module lazy-loading
const panda= () => import(/* webpackChunkName: "group-panda" */ "./components/panda/panda.vue");
// ...

export const appRoute = [
  {
    path: "",
    name: "root",
    redirect: '/index'
  },
  {
    path: "/index",
    name: "index",
    component: index
  },
  {
    path: "/panda",
    name: "panda",
    component: panda
  },
  //...
  {
    path: "**",
    name: "http404",
    component: http404
  }
];
所以panda模块是惰性加载的。 但是,当我导航到panda页面时,在App.vue的mounted()生命周期中使用this.$route.path的console.log()仅输出“/”,而不是“/ panda” 。 但是主页很好用,它显示预期的“/ index”。那么,当页面最初加载时,Vue路由器如何正确获取延迟加载页面的当前路径? 我错过了什么吗?编辑:然而,它可以在Webpack热重载后捕获正确的路径。在第一次访问panda时,它捕获“/”,但是在我更改源代码并进行webpack-dev-server热重载后,它会得到“/ panda”。所以我猜它与Vue生命周期有关。

这个问题很久以前就被问过了,而且在最近的vue.js版本中,它已经有了不错的webpack懒加载支持,看起来这不再是一个问题。 - Valorad
6个回答

92

有一个currentRoute属性对我有效:

this.$router.currentRoute

7
这对我也起作用了,应该采纳这个答案。参考链接:https://router.vuejs.org/api/#router-currentRoute - revobtz
1
我使用此代码出现“TypeError:cyclic object value”。 - trainoasis
16
这是Vue.js中的代码,用于获取当前页面的路由路径。 - Valorad
@SuitBoyApps:是的,它可以。 - 1_bug

36

糟糕!抱歉,我是指$route。那是一个打字错误,我已经更正了。 - Valorad
没有运气。当模块被延迟加载时,无论是 (<any>this.$router).history.current.path 还是 this.$route.path 都不能获得正确的路径。 - Valorad
我在你的示例中看到,$route和$router都可以使用,在这种情况下"/index"也是如此。但是/panda是懒加载的,它们仍然得到的是"/"而不是"/panda"。 - Valorad

28

使用this.$route.path。简单而有效。


2
这仅在组件内可用。$router 可在任何 js 中使用。 - Dean
1
我在HTML中使用了以下代码,它可以正常工作。v-if="$router.path === '/dashboard'" - Fthi.a.Abadi

3

在某些组件中使用当前路由路径来隐藏标题栏。

使用 this.$route.path 获取当前路由路径。

<navigation v-if="showNavigation"></navigation>

data() {
    this.$route.path === '/' ? this.showNavigation = false : this.showNavigation = true
}

1
如果您遇到类似的问题,正确的解决方法是使用router.onReady,然后调用与路径相关的逻辑。下面是官方Vue路由器文档:

router.onReady

签名:

router.onReady(callback, [errorCallback])

该方法会在路由完成初始导航时排队回调,这意味着它已解析与初始路由相关的所有异步进入钩子和异步组件。
这在服务器端渲染中非常有用,以确保服务器端和客户端输出的一致性。
第二个参数errorCallback仅在2.4+中支持。当初始路由解析遇到错误(例如无法解析异步组件)时,将调用它。
来源:https://v3.router.vuejs.org/api/#router-onready

router.onReady不是一个函数。 - fire in the hole
据我所见,文档已更新至v4,因此您需要查看v3-https://v3.router.vuejs.org/api/#router-onready。 - Thomas Kolasa
有没有其他的选择,像我一样使用v4的人? - fire in the hole
1
我认为你正在寻找这个:https://router.vuejs.org/api/#isready - Thomas Kolasa

0

针对Vue3的Composition API

只需定义变量route并赋值为const route = useRoute()即可使用route.path

用法示例

如果您尝试以下操作,每当路径发生更改时,它都会将当前路径记录到控制台:

<script setup>
 import {useRoute} from 'vue-router'

 const route = useRoute()

 watchEffect(() => console.log(route.path))
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接