• vue-router中vue生命周期的顺序


    1. vue-router 在 Vue 中的生命周期:

    这是 vue 生命周期的图:

    在路由中分别定义A页面和B页面

    A页面:

    <template>
      <div>
        <router-link to="/test2">去B页面</router-link>
      </div>
    </template>
    
    <script>
      export default {
        beforeCreate(){
          console.log('A页面 beforeCreate');
        },
        created(){
          console.log('A页面 created');
        },
        mounted(){
          console.log('A页面 mounted');
        },
        beforeDestroy(){
          console.log('A页面 beforeDestroy');
        },
        destroyed(){
          console.log('A页面 destroyed');
        }
      }
    </script>

    B页面:

    <template>
      <div>
        <router-link to="/test1">去A页面</router-link>
      </div>
    </template>
    
    <script>
      export default {
        beforeCreate(){
          console.log('B页面 beforeCreate');
        },
        created(){
          console.log('B页面 created');
        },
        mounted(){
          console.log('B页面 mounted');
        },
        beforeDestroy(){
          console.log('B页面 beforeDestroy');
        },
        destroyed(){
          console.log('B页面 destroyed');
        }
      }
    </script>

    从 A 页面跳到 B 页面:

    2. Vue-Router中,导航守卫的执行顺序:

     这里存在疑惑的是组件的生命周期到底在导航守卫的哪个阶段执行,测试代码如下:

    结论:从控制台结果可以看出,组件的生命周期是在Vue-Router导航守卫的DOM更新过程中执行的

    1. 导航被触发。
    2. 在失活的组件里调用离开守卫。
    3. 调用全局的 beforeEach 守卫。
    4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
    5. 在路由配置里调用 beforeEnter
    6. 解析异步路由组件。
    7. 在被激活的组件里调用 beforeRouteEnter
    8. 调用全局的 beforeResolve 守卫 (2.5+)。
    9. 导航被确认。
    10. 调用全局的 afterEach 钩子。
    11. 触发 DOM 更新。(此过程触发组件的生命周期)
    12. 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。

     这也就解释了切换路由时,两个组件生命周期执行的顺序是交叉的。

  • 相关阅读:
    剑指offer--50.滑动窗口的最大值
    剑指offer--49.矩阵中的路径
    剑指offer--48.机器人的运动范围
    剑指offer--47.数据流中的中位数
    剑指offer--46.字符流中第一个不重复的字符
    剑指offer--45.二叉树的深度
    剑指offer--44.两个链表的第一个公共结点
    剑指offer--43.连续子数组的最大和
    海盗分宝石问题
    C++数组名退化指针实例
  • 原文地址:https://www.cnblogs.com/momo798/p/13580434.html
Copyright © 2020-2023  润新知