7

我正在使用vueand构建一个应用程序vue-router。在某些路由中,我需要先检查一些条件,如果这些条件不满足,则重定向到另一个组件,所以我在我的组件选项activate上使用了钩子router,它工作正常。另外,在同一个组件中,我有 vuecreated钩子来加载一些数据,问题是如果我之前提到的那些条件不满足,那么我无法在 created 钩子中加载数据。我期望的是,如果不满足该条件,并且调用了重定向钩子,那么创建的钩子不会被触发,但实际发生的是,当该条件为假时,激活钩子的重定向被调用并且从 Vue 创建的钩子。因此,除了针对我的特定用例的解决方案之外,我还想知道一起使用 vue 和 vue 路由器时挂钩的执行顺序。

4

3 回答 3

9

对于 Vue 2.0:

  1. 之前创建
  2. 创建
  3. 安装前
  4. 安装
  5. 更新前
  6. 更新
  7. 之前销毁
  8. 毁坏

现在,当使用 vue-router 2.0 时,可以根据他们的文档在两个地方完成数据获取:

导航后获取:首先执行导航,并在传入组件的生命周期钩子中获取数据。在获取数据时显示加载状态。

导航前取数据:在路由进入守卫导航前取数据,取数据后进行导航。

对于您的情况,您可以在函数中编写数据获取逻辑,并在组件生命周期的“创建”挂钩中调用它。如果所有数据都随路由发生变化,则在 $route 对象上编写一个观察程序,这将触发您的数据获取功能。

由于 vue-router 0.7 的数据钩子已被弃用,而是 $route 对象已被设为响应式。在这里阅读更多。

于 2017-03-22T12:54:59.553 回答
2

也许你对In-Component Guards(使用 Vue Router 加载的组件中可用的附加钩子)感兴趣

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // called before the route that renders this component is confirmed.
    // does NOT have access to `this` component instance,
    // because it has not been created yet when this guard is called!
  },
  beforeRouteUpdate (to, from, next) {
    // called when the route that renders this component has changed,
    // but this component is reused in the new route.
    // For example, for a route with dynamic params `/foo/:id`, when we
    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
    // will be reused, and this hook will be called when that happens.
    // has access to `this` component instance.
  },
  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.
  }
}

https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

如果您使用 Vue + Vue 路由器并且您在 RouteA 并从它导航到 RouteB 并且每个路由/组件在“created”上注册某些东西(例如接收根支持的数据)并在“beforeDestroy”上取消注册但是当您离开 RouteA 时“beforeDestroy”在 RouteB “创建”之后被调用,所以你没有注册任何东西!我已经对其进行了测试,并且 VUE 1 的顺序正确。它必须在 VUE 2 + VUE Router 2 中的某个地方进行更改。

从 RouteA 到 RouteB 时,VUE 1 中正确/预期的钩子顺序:

  • RouteA beforeDestroy
  • RouteB 创建

从 RouteA 到 RouteB 时,VUE 2 中不正确/意外的钩子顺序:

  • RouteB 创建
  • RouteA beforeDestroy

解决方案是对 VUE 2 + VUE Router 2 使用“created”+“beforeRouteLeave”。

于 2019-01-03T09:42:00.013 回答
0

为什么不向每个日志添加控制台日志并亲自查看?

据我所知,无需测试:

  1. 可以重用
  2. 可以激活

-- 现在正在创建组件实例:

  1. 创建
  2. 编译前
  3. 编译

--(不确定是先准备好还是先激活,但我想准备好了)

  1. 准备好
  2. 启用
  3. 数据

对于您的特定情况,数据获取应该发生在数据挂钩中 - 毕竟这就是它的用途。

于 2016-04-05T12:36:21.863 回答