在 DOM 更改之前和路由本身之外更改路由时触发事件? [英] Fire event when changing route before DOM changes and outside the route itself?

查看:27
本文介绍了在 DOM 更改之前和路由本身之外更改路由时触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几天前打开了

但是,您可以利用 JavaScript 钩子.有一个名为 leave 的 JavaScript 钩子,您可以在 DOM 更改之前访问它.

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

为此,您需要将元素包装在 包装组件.

即.

...

方法:{离开(埃尔,完成){//访问 DOM 元素完毕()}}

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

解决方案

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

这篇关于在 DOM 更改之前和路由本身之外更改路由时触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆