vue-router 各种守卫以及流程梳理

文档连接:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

全局守卫:我写了一个 routerIntercopter.js

// 路由拦截器
import router from "./router";

router.beforeEach((to,from,next) => {
    // 路由全局前置守卫
    console.log(from.path,"---全局前置守卫--->",to.path);
    next()
});

router.beforeResolve((to,from,next) => {
    // 全局解析守卫
    console.log(from.path,"---全局解析守卫--->",to.path)
    next()
})

router.afterEach((to,from) => {
    // 全局后置守卫
    console.log(from.path,"---全局后置守卫--->",to.path)
})

组件内局部守卫:

<script>
export default {
    data(){
        return{
            
        }
    },
    beforeRouteEnter(to,from,next){
        // 组件内
        // 在渲染该组件的对应路由被 confirm 前调用
        // 不!能!获取组件实例 `this`
        // 因为当守卫执行前,组件实例还没被创建
        next(vm => {
            console.log(from.path,"---进入--->",to.path);
        })
    },
    beforeRouteUpdate (to, from, next) {
     //vue 2.2开始支持
// 这个钩子有点异常强大,可以监听到 params或者query参数放生改变!!! 之前用watch监听,存在很多问题,而这个钩子实在是实用!! 但是要注意如果params后query没有发生改变,是不会触发此钩子的 // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` console.log(from.path,"---更新--->",to.path); next() }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` console.log(from.path,"---离开--->",to.path); next() } } </script>

下面来看一下执行顺序:

进入此页面时:

 离开此页面时:

 不同参数(params或query不同 页面切换时)

 以上就能很清晰的看出不同情况的执行顺序!!

原文地址:https://www.cnblogs.com/fqh123/p/13512022.html