2月13日-vue-cli 路由前置守卫

Profile Picture
- Published on Feb 13, 2020🌏 Public

路由前置守卫

当我们需要在正式访问加载页面组件之前去做判断,满足某个条件的时候正常访问,不满足条件时,跳转到指定页面去。

经常被用来处理未登录用户访问页面时进行跳转

{
  //to:目标路由对象
  //from:当前真要离开的路由
  //next:函数,通过函数实现放行或者拒绝
  beforeEnter:(to,from,next)=>{


  }
}
new Vue({
  router: new Router({
    mode: 'history',
    routes: [
      {
        name: "login",
        path: "/login",
        component: () => import('./components/login')
      }, 
      {
        name: "test",
        path: "/test",
        component: () => import('./components/test')
      },{
        name: "home",
        path: '/home',
        component: () => import("./components/home"),
        beforeEnter:(to,from,next)=>{
          console.log(to)  //目标路由状态数据
          console.log(from) //当前页路由状态数据
          //允许访问
          //next()

          //拒绝:
          //方式1:
          next(false) //阻止进入,在页面中执行跳转会阻止,地址不变,如果浏览器直接输地址,会跳到首页
          
          //方式2:重定向,next函数传入一个重定向参数
          // next({
          //   path:'/login'
          // })
        }
      }
    ]
  }),
  render: h => h(App),
}).$mount('#app')