vue - 路由守卫

路由守卫

    1. 作用: 对路由进行权限控制

    2. 分类: 全局守卫、独享守卫、组件内守卫

    3. 全局守卫:

// 全局前置路由守卫 —— 初始化之前和路由切换之前被调用。
router.beforeEach = (to, from, next) => { console.log('前置路由守卫', to, from) if (to.meta.isAuth) { if (localStorage.getItem('school') === 'atguigu') { next() // 放行 } else { alert('学校名不对,无权限查看!') } } else { next() } } // 全局后置路由守卫 —— 初始化的时候被调用、每次路由切换之后被调用 router.afterEach((to, from) => { console.log('后置路由守卫', to, from) document.title = to.meta.title || '硅谷系统' })

    4. 独享守卫:单个路由的守卫

{
    name: 'xinwen',
    path: 'news',
    component: News,
    meta: { isAuth: true, title: '新闻' },
    beforeEnter: (to, from, next) => {
        if (to.meta.isAuth) {
            if (localStorage.getItem('school') === 'atguigu') {
                next()
            } else {
                alert('学校名不对,无权限查看!')
            }
        } else {
           next()
        }
    }
}    

5. 组件内的路由守卫 (不常用),都是前置守卫

    // 通过路由规则,进入该组件时被调用

    beforeRouteEnter(to, from, next) {}

    // 通过路由规则,离开该组件时被调用

    beforeRouteLeave(to, from, next) {}

posted @ 2022-01-02 19:05  我就尝一口  阅读(227)  评论(0编辑  收藏  举报