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.
We can use this. $router. currentRoute. path property in a vue router component to get the current path.
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.
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!
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.
There is a currentRoute
property that worked for me: this.$router.currentRoute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With