5

I'm quite new to Vue, hopefully this won't be a very stupid question :)

The beforeDestroy gets fired after the DOM structure changes.

I've tried using beforeUpdate and updated events, but none seems to fire before the DOM changes.

Reproduction online: https://jsfiddle.net/p2c3b10t/18/ (check the console)

1
  • 1
    Not a stupid question at all. I was really liking Vue, but I hate that beforeDestroy and destroyed do not work the way you would expect. From what I read and have been told, the parent has to initiate beforeDestroy of a component. So the beforeDestroy is not a part of the regular lifecycle. Very stupid, as this works perfectly in React with the use of componentWillUnmount(). Thanks for your question as it received an excellent solution. Commented Jun 15, 2019 at 23:50

1 Answer 1

5

When dealing with routing with Vue Router, instead of relying on the lifecycle hooks, use navigation guards. These guards hook into the route navigation process and can be either global, per-route, or in-component.

In this particular case, we are looking for the beforeRouteLeave in-component guard.

beforeRouteLeave (to, from, next) {
  // called when the route that renders this component is about to
  // be navigated away from.
  // has access to `this` component instance.
}

In this guard, we can access to and from, and call next.

export type NavigationGuard = (
  to: Route,
  from: Route,
  next: (to?: RawLocation | false | ((vm: Vue) => any) | void) => void
) => any
  • to is the target Route being navigated to.

  • from is the current Route being navigated away from.

  • next is the function that must be called to resolve the hook

After performing the logic inside this guard, one must call next() to resolve the hook.


Revised JSFiddle

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome answer! Very well explained! Thanks for that @Ricky!
Thanks! I am happy to help you @Alvaro 😃.
Hey Ricky, I opened a similar issue. My problem is I can not rely on external routes to fire my event. See the full question here: stackoverflow.com/q/52593490/1081396

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.