Fire event when changing route before DOM changes and outside the route itself?

烈酒焚心 提交于 2019-12-11 06:59:58

问题


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')

回答1:


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:

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()
  }
}


来源:https://stackoverflow.com/questions/52593490/fire-event-when-changing-route-before-dom-changes-and-outside-the-route-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!