1.简单介绍
    导航守卫主要用来通过跳转或取消的方式守卫导航(导航表示路由正在发生改变),当需要在路由跳转前做一些验证(登录验证)时,就需要使用vue-router 导航守卫
    2.全局前置导航守卫 router.beforeEach

    1. const router=new vueRouter({
    2. routes:[
    3. {
    4. path:'/foo',
    5. component:Foo,
    6. meta:{
    7. auth:true
    8. },
    9. children:[{
    10. path:'bar',
    11. component:Bar
    12. }]
    13. }
    14. ]
    15. })
    16. router.beforeEach((to,from,next)=>{
    17. if(to.matched.some(val=>val.meta.auth)){
    18. next('/login?returnUrl='+to.path) //跳转至该路由并传参url
    19. }else{
    20. next() 一定要调用next(),来执行下一步操作
    21. }
    22. })

    导航守卫方法接收三个参数

    • to:即将要进入的目标路由对象
    • from:当前要离开的路由对象
    • next: 是一个函数,执行效果依赖next方法的调用参数
      • next()进入管道中的下一个钩子
      • next(false)中断当前的导航
      • next(‘/‘)跳转到不同的地址(括号中为要跳的路由地址)

    3.组件内的守卫

    1. @click="$router.push({ name: 'address', params: { city}})"
    2. beforeRouteEnter (to, from, next) {
    3. next(vm => {
    4. // 通过 `vm` 访问组件实例
    5. vm.city=to.params.city
    6. })
    7. }