1

I opened a similar topic a few days ago, where I was suggested to use beforeRouteLeave within the route component definition.

However, I'm creating a Vue component and I won't have control over how developers wants to define their route components. Therefore, I need a way to fire an event within my own component and don't rely on external route components.

When changing from one route to another, the beforeDestroy gets fired after the DOM structure changes.

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

import Vue from 'vue'
import MyComponent from '../myComponent/' // <-- Need to fire the event here 
import router from './router'

Vue.use(MyComponent)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
}).$mount('#app')
Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • I don't understand why you can't define a `beforeRouteLeave` inside of your `MyComponent`? – Steven B. Oct 01 '18 at 15:00
  • `beforeRouteLeave` is a [navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards). It seems they can only be used within route components. – Alvaro Oct 01 '18 at 15:17
  • Sorry for asking, but what is it that you need to accomplish? Because i dont understand. If you build a component why not add a event handler which can be assigned, so the end developer can assign a `beforeRouteLeave` event to the component, and you can write the code for this even already, then you only need to check if the event handler is assigned. – Ernst Reidinga Oct 01 '18 at 14:52

1 Answers1

2

In the Vue instance lifecycle, the hook beforeDestroy gets called once the DOM has changed.

You are most likely looking for a beforeUnmount hook, which would be in-between mounted and beforeDestroy, but that is not available:

lifecycle vue

However, you could take advantage of JavaScript hooks. There is a JavaScript hook called leave, where you can access the DOM before it changes.

leave: function (el, done) {
  // ...
  done()
},

For this to work, you would need to wrap your element in a <transition> wrapper component.

ie.

<transition
  :css="false"
  @leave="leave"
>
  <div>
    <!-- ... -->
  </div>
</transition>

...

methods: {
  leave(el, done) {
    // access to DOM element
    done()
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307
Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53