Vue路由守卫


Vue 路由守卫

router.beforeEach: 全局前置路由守卫,每次切换之前被调用,可以做权限拦截
router.afterEach: 全局后置路由守卫,每次切换之后调用, 可用于切换document.title
router.beforeEnter: 独享路由守卫,只有前置,没有后置,写在routes配置项里
router.beforeRouteEnter: 组件内路由守卫, 写在组件中,路过路由规则进入该组件时被调用
router.beforeRouteLeave: 组件内路由守卫, 写在组件中,路过路由规则离开该组件时被调用

全局前置路由守卫

router.beforeEach((to,from,next)=>{})
每次前置路由守卫都要调next方法,否则无法继续

全局后置守卫

router.afterEach((to,from)=>{})

独享路由守卫

router.beforeEnter((to,from,next)=>{})

组件内路由守卫

router.beforeRouteEnter((to,from,next)=>{}): 组件内路由守卫, 写在组件中,路过路由规则进入该组件时被调用
router.beforeRouteLeave((to,from,next)=>{}): 组件内路由守卫, 写在组件中,路过路由规则离开该组件时被调用

案例

main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import router from './router'

// 关闭Vue的生产提示
Vue.config.productionTip = false

Vue.use(VueRouter)


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

// 全局路由后置守卫
router.afterEach((to,from)=>{
  console.log('afterEach',to,from);
})



// 创建Vue实例
new Vue({
  // 将app组件放入容器中
  render: h => h(App),
  router
}).$mount('#app')

router/index.js

import VueRouter from 'vue-router'
import Island from '../pages/Island'
import Polaris from '../pages/Polaris'

export default new VueRouter({
    routes: [
        {
            component: Island,
            path: "/Island",
            props: ($routes) => ({
                id: $routes.query.id,
                title: $routes.query.title
            })
        },
        {
            component: Polaris,
            path: "/Polaris",
            // 组件独享路由守卫
            beforeEnter:(to,from,next)=>{
                next()                
            }
        },
    ]
})


island.vue






vue