在 DOM 更改之前使用 vue-router 更改路由时触发事件? [英] Fire event when changing route with vue-router before DOM changes?

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

问题描述

我对 Vue 很陌生,希望这不会是一个非常愚蠢的问题:)

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

beforeDestroy 在 DOM 结构改变后被触发.

The beforeDestroy gets fired after the DOM structure changes.

我尝试使用 beforeUpdateupdated 事件,但在 DOM 更改之前似乎没有触发.

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

在线复制:https://jsfiddle.net/p2c3b10t/18/(检查控制台)

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

推荐答案

当使用 Vue Router 处理路由时,而不是依赖于生命周期钩子,使用导航守卫.这些守卫挂钩到路由导航过程中,可以是 全局per-route组件内.

在这种特殊情况下,我们正在寻找 beforeRouteLeave 组件内保护.

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.
}

在这个守卫中,我们可以访问tofrom,并调用next.

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 是导航到的目标路由.

    • to is the target Route being navigated to.

      from 是当前导航离开的路线.

      from is the current Route being navigated away from.

      next 是解析钩子必须调用的函数

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

      执行完这个守卫内部的逻辑后,必须调用next()来解析钩子.

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

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

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