当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue-router之导航守卫

vue-router之导航守卫

2020年07月15日  | 移动技术网IT编程  | 我要评论

正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。

你可以使用 router.beforeEach 注册一个全局前置守卫:

const router = new VueRouter({ ... })

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

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中

每个守卫方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象
  •  from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
  1.  next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
  2. next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
  3. next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
  4. next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
//router文件内的内容

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);

引入组件省略,按照自己的方式写就行

const routes= [{
  path: '/',
  redirect: '/Home',
  component: IndexPage,
  children:[{
    path: 'Home',
    component: Home,
  },{
    path: 'Center',
    component: Center,
  },{
    path: 'Repay',
    component: Repay,
  }]
},{
  path:"/SignIn",
  component: SignIn,
  meta:{online:true}
},{
  path:"/Reg",
  component: Reg,
  meta:{online:true}
},{
  path:"/Forget",
  component: Forget,
  meta:{online:true}
}];
const router = new VueRouter({
  routes
});
router.beforeEach((to, from, next) => {
  if(to.meta.online){//进入的导航如果存在meta,并且online为true,可以正常进入
    next()
  }else {//进入的导航如果不存在meta,
    let online=localStorage.getItem('online');//获取本地存在的online
    if(online=='true'){//如果本地存在的online
      next()
    }else {//如果不存在online,或者online为false
      localStorage.clear();
      next({path:'/SignIn'});
    }
  }
});

 

 

 

本文地址:https://blog.csdn.net/qq_42089654/article/details/85989874

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网