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

JavaScript

EvaPro

2020-03-12

我有一个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
  }
];

因此,Pandas模块是延迟加载的。但是,当我导航到panda页面时,this.$route.pathin App.vuemounted()生命周期中的console.log()仅输出

“ /”

代替

“/Pandas”

但是索引页效果很好,它可以准确显示

“/指数”

如预期的那样。

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

编辑:

但是,在Webpack热重新加载后,它可以捕获正确的路径。首次访问时panda它捕获到“ /” ,但是在我更改了源代码中的内容后,webpack-dev-server进行了热重载,然后得到了“ / panda”。

因此,我认为这与Vue生命周期有关。

第889篇《Vue路由器如何在页面加载时获取延迟加载模块的当前路由路径?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
猿飞云斯丁 2020.03.12

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

在这里检查:https : //jsfiddle.net/nikleshraut/chyLjpv0/19/

你也可以$router这样

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

凯斯丁 2020.03.12

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

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

<navigation v-if="showNavigation"></navigation>
data() {
    this.$route.path === '/' ? this.showNavigation = false : this.showNavigation = true
}
西里Near 2020.03.12

有一个currentRoute对我有用物业:this.$router.currentRoute

阿飞飞云 2020.03.12

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android