How can Vue router get current route path of lazy-loaded modules on page load?

空扰寡人 提交于 2020-02-27 13:50:27

问题


I have a vue app with router set up like:

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
  }
];

So the panda module is lazy-loaded. However, when I navigate to panda page, a console.log() of this.$route.path in App.vue's mounted() lifecycle only outputs

"/"

instead of

"/panda"

But index page works well, it shows exactly

"/index"

as expected.

So how can Vue router get current path correctly of a lazy-loaded page, when page is initially loaded? Did I miss something?

Edit:

It can, however, catch the correct path after Webpack hot-reloads. It catches "/" on first visit of panda, but after I change something in source code, webpack-dev-server hot-reloads, then it gets "/panda".

So I guess it has something to do with Vue life-cycle.


回答1:


There is a currentRoute property that worked for me: this.$router.currentRoute




回答2:


May be you need to use $route not $router

check here : https://jsfiddle.net/nikleshraut/chyLjpv0/19/

You can also do it by $router this way

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




回答3:


Use this.$route.path. Simple and effective.




回答4:


Hide Header in some components using the current route path.

get current route path using this.$route.path

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


来源:https://stackoverflow.com/questions/47170533/how-can-vue-router-get-current-route-path-of-lazy-loaded-modules-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!