Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 264
Valorad Avatar asked Nov 08 '17 02:11

Valorad


People also ask

How do I find the current path on my vue router?

We can use this. $router. currentRoute. path property in a vue router component to get the current path.

What is lazy loading in vue router?

vue file. Lazy loading refers to an approach by which all the scripts are not loaded on the DOM as the application starts. Instead, they're only loaded when requested, which makes the JavaScript bundle size very small at initial load. Vue.

How does vue routing work?

Vue Router uses special link elements called <router-link> that have a to attribute that map to a component. When we run our app, we should see our home component rendering. If we click our router-link elements, the content will change and the URL will too!

How do you refresh a page on a vue router?

To reload a route with Vue Route, we can call the this. $router.go() method. If it has no arguments, then it'll reload the current route. This way, it'll notice when the path changes and it'll trigger a reload of the component with new data.


1 Answers

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

like image 57
Andre Avatar answered Sep 24 '22 11:09

Andre