Sunday, October 16, 2022

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

Issue

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.


Solution

There is a currentRoute property that worked for me:

this.$router.currentRoute


Answered By - Andre
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.