Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing app inside beforeRouteEnter

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.

like image 993
schellmax Avatar asked Mar 14 '18 11:03

schellmax


Video Answer


1 Answers

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

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:

beforeRouteEnter (to, from, next) {
  next(vm => {
    vm.$root.loading = true;
  })
}
like image 191
Laurynas Avatar answered Jan 26 '23 02:01

Laurynas