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

Val*_*rad 29 javascript vue.js vue-router

我有一个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
  }
];
Run Code Online (Sandbox Code Playgroud)

所以熊猫模块是懒惰的.然而,当我导航到panda的页面,一个的console.log()this.$route.pathApp.vuemounted()生命周期仅输出

"/"

代替

"/熊猫"

但索引页面运行良好,它完全显示

"/指数"

正如所料.

那么,当页面最初加载时,Vue路由器如何才能正确获取延迟加载页面的当前路径?我错过了什么?

编辑:

但是,它可以在Webpack热重新加载后捕获正确的路径.它在第一次访问时捕获"/" panda,但在我更改了源代码中的内容后,webpack-dev-server热重新加载,然后它获得"/ panda".

所以我猜这与Vue生命周期有关.

And*_*dre 38

有一个currentRoute适合我的房产:this.$router.currentRoute

  • `this.$router.currentRoute.path` ✔ (13认同)
  • 这也为我工作,这应该是公认的答案。供参考:https://router.vuejs.org/api/#router-currentroute (5认同)

Nik*_*aut 29

可能是你需要使用$route$router

点击这里:https://jsfiddle.net/nikleshraut/chyLjpv0/19/

您还可以通过做$router这样

https://jsfiddle.net/nikleshraut/chyLjpv0/20/


Nun*_*iro 12

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

  • 这仅在组件内可用。$router 在任何 js 中都可用 (2认同)