How can Vue router get current route path of lazy-

2020-06-30 03:59发布

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.

4条回答
做自己的国王
2楼-- · 2020-06-30 04:43

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

查看更多
啃猪蹄的小仙女
3楼-- · 2020-06-30 04:46

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
}
查看更多
家丑人穷心不美
4楼-- · 2020-06-30 04:55

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

查看更多
手持菜刀,她持情操
5楼-- · 2020-06-30 05:00

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/

查看更多
登录 后发表回答