假设从组件Home导航到组件About,则会经过以下几个路由的钩子函数和组件生命周期。会分为两种情况。
一 初始化第一个页面
无论是SPA还是MPA都会有一个默认的初始化首页。这个初始化页面会按顺序经过如下各种钩子:
导航钩子/组件生命周期 | 触发对象 | 说明 |
---|---|---|
1. 全局前置守卫 beforeEach(to, from, next) | this.$router | 导航钩子全局路由级级别 |
2. Home组件 路由独享守卫 beforeEnter(to, from, next) | this.$route | 导航钩子当前激活路由级别(进入) |
3. Home 组件 beforeRouteEnter(to, from, next) | Home 组件 | 导航钩子当前激活组件级别(进入) |
4. 全局解析守卫 beforeResolve(to, from, next) | this.$router | 导航钩子全局路由级级别 |
5. 全局后置钩子 afterEach(to, from) | this.$router | 导航钩子全局路由级级别 |
6. Home 组件 beforeCreate 生命周期 | Home 组件 | 组件生命周期 |
7. Home 组件 Created 生命周期 | Home 组件 | 组件生命周期 |
8. Home 组件 beforeMount 生命周期 | Home 组件 | 组件生命周期 |
9. Home 组件 mounted 生命周期 | Home 组件 | 组件生命周期 |
二 当从Home导航到About
导航钩子/组件生命周期 | 触发对象 | 说明 |
---|---|---|
1. Home 组件 beforeRouteLeave(to, from, next) | Home 组件 | 导航钩子当前失活路由级别(离开) |
2. 全局前置守卫 beforeEach(to, from, next) | this.$router | 导航钩子全局路由级级别 |
3. About 组件 路由独享守卫 beforeEnter(to, from, next) | this.$route | 导航钩子当前激活路由级别(进入) |
4. About 组件 beforeRouteEnter(to, from, next) | About 组件 | 导航钩子当前激活组件级别(进入) |
5. 全局解析守卫 beforeResolve(to, from, next) | this.$router | 导航钩子全局路由级级别 |
6. 全局后置钩子 afterEach(to, from) | this.$router | 导航钩子全局路由级级别 |
7. About 组件 beforeCreate 生命周期 | About 组件 | 组件生命周期 |
8. About 组件 Created 生命周期 | About 组件 | 组件生命周期 |
9. About 组件 beforeMount 生命周期 | About 组件 | 组件生命周期 |
10. Home 组件 beforeDestroy 生命周期 | Home 组件 | 组件生命周期 |
11. Home 组件 destroyed 生命周期 | Home 组件 | 组件生命周期 |
12. About 组件 mounted 生命周期 | About 组件 | 组件生命周期 |
总结规律
beforeMount
后,mounted
前,旧组件发生 beforeDestroy
和destroyed
beforeRouteLeave(to, from, next)**
,再执行全局路由级别的前置导航钩子beforeEach(to, from, next)
,否则直接执行全局路由级别的前置钩子beforeEnter(to, from, next)
beforeRouteEnter(to, from, next)
beforeResolve(to, from, next)
和afterEach(to, from)