I'd like to show some loading animation in the app root while a component prepares to be rendered by vue router.
Already found this question, proposing the use of navigation guards, and another question, where the accepted answer shows how to use the beforeEach
guard to set a variable in app
, showing a loading animation.
The problem is that this doesn't work when deep-linking to some route (initial url includes a route path, such as 'someurl#/foo'). The beforeEach
guard simply doesn't get called then.
So i switched to the loaded component's beforeRouteEnter
guard, which would also allow me to show the loading animation for some components only:
app:
var app = new Vue({
el: '#app',
data: { loading: false }
router: router
});
component:
var Foo = {
template: '<div>bar</div>',
beforeRouteEnter: function(to, from, next) {
app.loading = true; // 'app' unavailable when deep-linking
// do some loading here before calling next()...
next();
}
}
But then i found that when deep-linking to the component, app
isn't available in beforeRouteEnter
, as it gets called very early in the initialisation process.
I don't want to set loading
to true
inside the app data declaration, as i might decide at some point to deep-link to another route, whose component doesn't need a loading animation.
I believe, your solution is correct. However, I would suggest using next() function instead. As written in vue-router docs. https://router.vuejs.org/en/advanced/navigation-guards.html
What about using
beforeRouteLeave
to trigger the loading then have the component toggle it off inmounted
.For the initial load of the app you could have
app:
then for your components
component:
Found a workaround using Vue.nextTick:
Feels a little hacky, so would be thankful for other suggestions.
Find a demo of this solution here: https://s.codepen.io/schellmax/debug/aYvXqx/GnrnbVPBXezr#/foo