2
votes

I'm seeing some behaviour I don't understand in the beforeRouteEnter navigation guard with vue.js/vue-router. I understand from the docs that this guard "does NOT have access to this component instance", but that if you need to get access to the component instance you can do so by means of a callback. I've done this because I want to abort the route change if one of the props hasn't been defined (normally because of a user clicking a forward button). So this is what I have:

beforeRouteEnter(to, from, next) {
  console.log("ProductDetail: routing from = "+from.path+" to "+to.path);

  next(vm => {
    if (!vm.product) {
      console.log("Product empty: routing back one page");
      vm.$router.go(-1);
    }
  });
},

The idea is that I test for the existence of the prop and if it's not valid, go back (or otherwise abort the route change). From the console log, I can see that what is happening, though, is that the component instance is in fact getting created, presumably as a result of the callback being called, and throwing a bunch of errors, before the vm.$router.go(-1) kicks in and takes the user back to the previous screen.

So what, if anything, can I do to actually prevent the route change from completing if one of the requisite conditions isn't present, if it's too late by the time I can test for it?

1

1 Answers

3
votes

You can try this code

beforeRouteEnter(to, from, next) {
  // Your code
  next(vm => {
    if (!vm.product) {
      console.log("Product empty: routing back one page");
      next(from)
    }
  });
}

You can read more about this guard in https://router.vuejs.org/en/advanced/navigation-guards.html