vue-router 全局前置路由守卫和后置路由守卫

阿里云教程3个月前发布
17 0 0

index.js路由配置文件

  • 全局前置路由守卫
    有路由间的切换就会调用,调用前先验证是否有权限,满足条件则可以切换

// 全局前置路由守卫---检查是否符合跳转条件,列如taobao里点击个人中心,检查是否登录了
router.beforeEach((to,from,next) => {
  // 点击了哪个组件,可以拿到这个组件的url、path等信息
  console.log( to: ,to)
  // 从哪个组件跳转过来,可以拿到这个组件的url、path等信息
  console.log( from ,from)
  // 要调用next()才能真的跳转
  console.log( next ,next())
})
// 使用统一暴露,方便对路由的控制
export default router

vue-router 全局前置路由守卫和后置路由守卫


index.js路由配置文件

  • 用一个变量演示跳转条件,满足就跳转,实际生产这个变量可能是token、session、cokie,用于用户鉴权

let num = 6

router.beforeEach((to,_,next) => {
  console.log(to)
  const test = 4
  // 跳到哪个路由组件(每个组件都有自己的路由规则),用to这个参数,它能获取到组件的path、name之类的,to获取到的这些属性就是$route
  //只要点击组件名为name或path 为/home/message其中任意一个组件走if
  if(to.name ===  a  || to.path ===  /home/message ){
    if(test === num){
      next()
    }
  } else{ //点击的不是tongzhi或message其中任意一个组件,直接跳转到刚刚点击的组件
    next()
  }
 
})


index.js文件

let num = 6

router.beforeEach((to,_,next) => {
  console.log(to)
  const test = 4
  // 如果要跳转是,许多组件都有判断是否满足条件才能跳转,会造成if里面的语句会很长,我们可以立个flag,flag为true的就判断
  // 添加自定义属性flag(名字可以随意取)要在自己的路由规则里面添加meta这个对象,
  //再添加自定义属性flag
  // if(to.name ===  a  || to.path ===  /home/message ){
    if(to.meta.flag === true){
    if(test=== num){
      next()
    }
  } else{ //直接跳转
    next()
  }
 
})
// 要转成统一暴露,方便对路由的控制
export default router

index.js文件

在meta属性添加自定义属性

{
   path: /about ,
   meta:{
    flag:false,
    title: 关于 
   },
   component:About
  },
  {
   path: /home ,
   meta:{
    flag:false,
    title: 主页 
   }


index.js文件

  • 全局后置路由守卫

// *******************************************
// 全局后置路由守卫---跳转到点击的路由组件后,再进行一些调整,列如给路由组件起标题
// 只有两个参数,分别是to和from,和前置守卫一样可以拿到路由组件的参数,没有next参数
//用于分析、更改页面标题、声明页面等辅助功能
router.afterEach((to) => {
  console.log( 更改了页面标题 )
//点击该路由组件,且成功跳转到这个路由组件了,这样就可以修改组件的标题
  document.title = to.meta.title ||  自主练习 
})

vue-router 全局前置路由守卫和后置路由守卫

index.js文件

  • 设置组件标题(也叫url标题),这个标题也是自定义的属性,在meta添加

 {
   path: /about ,
   meta:{
    flag:false,
    title: 关于 
   },
   component:About
  },
  {
   path: /home ,
   meta:{
    flag:false,
    title: 主页  // meta添加了title
   },
   component:Home,
   children:[
    {
     name: a ,
     path: tongzhi ,
     meta:{
      flag:true,
      title: 通知 
     },
     component:TongZhi
    },


index.html(public文件夹下面的index.html)

为了防止刷新的时候,标题会显示项目的name(package.json文件的name),把index.html里面的title标签体修改一下

<!-- 修改默认title -->
    <!-- <title><%= htmlWebpackPlugin.options.title %></title> -->
    <title>自主练习</title>

© 版权声明

相关文章

暂无评论

none
暂无评论...