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

Viewed 130262

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.

5 Answers

There is a currentRoute property that worked for me:

this.$router.currentRoute

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

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
}

If You have similar problem the correct answer is to use router.onReady and then calling your logic concerning path. Below the official Vue router docs:

router.onReady

Signature:

router.onReady(callback, [errorCallback])

This method queues a callback to be called when the router has completed the initial navigation, which means it has resolved all async enter hooks and async components that are associated with the initial route.

This is useful in server-side rendering to ensure consistent output on both the server and the client.

The second argument errorCallback is only supported in 2.4+. It will be called when the initial route resolution runs into an error (e.g. failed to resolve an async component).

Source: https://v3.router.vuejs.org/api/#router-onready

Related