• 导航守卫


    什么是导航守卫

    • vue-router提供的导航守卫主要用来监听路由的进入和离开
    • vue-router提供了beforeEach()和afterEach()等钩子函数,这些钩子函数分别会在路由改变前后触发,正是这些钩子函数构成了导航守卫
    • 记住参数或查询的改变并不会触发进入/离开的导航守卫

    导航守卫的使用

    • 在路由中可以通过元数据meta来定义页面标题
    {
        path: '/home',
            component: Home,
            meta: { 
                title: '首页'  
            }
    },
    {
        path: '/about',
            component: About,
            meta: {
                title: '关于'  
            }
    }
    

    全局前置守卫

    • beforeEach()

    • 当一个路由跳转到另一个路由前就会触发

    • beforeEach()的使用格式:router.beforeEach( (to, from, next) => { } )

      • to:即将要进入的目标的路由对象
      • from:当前导航即将要离开的路由对象
      • next:调用该方法后才能进入下一个钩子
        • next()在不传入参数时,默认跳转到下一个页面
        • next()方法中可以传入路径,如next('/')或next( {path:'/'} ),当前导航被中断,跳转到指定路径
    • 利用导航守卫beforeEach()修改页面标题

    router.beforeEach((to, from, next) => {
        document.title = to.matched[0].meta.title
        next()
    })
    

    全局后置守卫

    • afterEach()

    • 当所有组件内守卫以及异步路由组件都被解析后调用

    • afterEach()的使用格式:router.afterEach( (to, from) => { } )

    • afterEach与beforeEach很相似,不同的是,afterEach()的参数只有两个,没有next,不需要手动调用next()方法,内部自动调用

    router.beforeEach((to, from) => {
        document.title = to.matched[0].meta.title
    })
    

    路由独享的守卫

    • beforeEnter

    • beforeEnter是写在某个路由的里面,只有在进入该路由前才会调用

    • beforeEnter()的使用格式:beforeEnter( (to, from, next) => { } )

    • 与beforeEach几乎相似

      {
        path: '/about',
        component: About,
        meta: {   title: '关于'  },
        beforeEnter: (to, from, next) => {
            console.log('beforeEnter')
            next()
        }
      }
      

    [更多导航守卫请查阅:] (https://router.vuejs.org/zh/guide/advanced/navigation-guards.html)

  • 相关阅读:
    动态多条件查询分页以及排序(一)MVC与Entity Framework版url分页版
    关于MVC3种IOC自写方法GetItems("Model名字")得到的Model为空的解决方法
    css中!important 的使用
    MVc4阅读后总结
    jquery方法off()
    关于backgroundpostion 火狐和其他浏览器的不同
    Random.Next
    sort(function(a,b){return ab})是什么
    js 简单的自制分组(类似于分页) 结合mvc3
    Discus 论坛 使用方法
  • 原文地址:https://www.cnblogs.com/jincanyu/p/14351396.html
Copyright © 2020-2023  润新知