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

2022-06-22  本文已影响0人  tutututudou

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
beforeEach.PNG

index.js路由配置文件

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 || '自主练习'
})
url标题.PNG

index.js文件

 {
   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>
上一篇 下一篇

猜你喜欢

热点阅读