Skip to content

35. Vue Router 守卫

35.1 actived deactived

activateddeactivated 是路由组件所独有的两个钩子,用于捕获路由组件的激活状态具体使用

  1. activated 路由组件被激活时触发
  2. deactivated 路由组件失活时触发

vue
<template>
  <ul>
    <li :style="{opacity}">欢迎学习vue</li>
    <li>news001 <input type="text"></li>
    <li>news002 <input type="text"></li>
    <li>news003 <input type="text"></li>
  </ul>
</template>

<script>
export default {
  name: 'News',
  data() {
    return {
      opacity: 1
    }
  },
  activated() {
    console.log('News组件被激活了')
    this.timer = setInterval(() => {
      this.opacity -= 0.01
      if (this.opacity <= 0) this.opacity = 1
    }, 16)
  },
  deactivated() {
    console.log('News组件失活了')
    clearInterval(this.timer)
  }
}
</script>

35.2 路由守卫

作用:对路由进行权限控制

分类:全局守卫、独享守卫、组件内守卫

35.2.1 全局守卫

meta 路由元信息

js
// 全局前置守卫:初始化时、每次路由切换前执行
router.beforeEach((to,from,next) => {
	console.log('beforeEach',to,from)
	if(to.meta.isAuth){ // 判断当前路由是否需要进行权限控制
		if(localStorage.getItem('school') === 'atguigu'){ // 权限控制的具体规则
			next()	// 放行
		}else{
			alert('暂无权限查看')
		}
	}else{
		next()	// 放行
	}
})

// 全局后置守卫:初始化时、每次路由切换后执行
router.afterEach((to,from) => {
	console.log('afterEach',to,from)
	if(to.meta.title){ 
		document.title = to.meta.title //修改网页的title
	}else{
		document.title = 'vue_test'
	}
})

35.2.2 独享守卫

js
beforeEnter(to,from,next){
	console.log('beforeEnter',to,from)
    if(localStorage.getItem('school') === 'atguigu'){
        next()
    }else{
        alert('暂无权限查看')
    }
}

35.2.3 组件内守卫

vue
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {... next()},

//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {... next()},

35.2.4 全局路由守卫

src/router/index.js

js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'


//创建一个路由器
const router = new VueRouter({
  routes: [
    {
      name: 'guanyv',
      path: '/about',
      component: About,
      meta: { title: '关于' }
    },
    {
      name: 'zhuye',
      path: '/home',
      component: Home,
      meta: { title: '主页' },
      children: [
        {
          name: 'xinwen',
          path: 'news',
          component: News,
          meta: { isAuth: true, title: '新闻' }
        },
        {
          name: 'xiaoxi',
          path: 'message',
          component: Message,
          meta: { isAuth: true, title: '消息' },
          children: [
            {
              name: 'xiangqing',
              path: 'detail',
              component: Detail,
              meta: { isAuth: true, title: '详情' },
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title,
                }
              }
            }
          ]
        }
      ]
    }
  ]
})

// 💖💖💖全局前置路由守卫————初始化的时候、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  console.log('前置路由守卫', to, from)
  if (to.meta.isAuth) {
    if (localStorage.getItem('school') === 'atguigu') {
      next()
    } else {
      alert('学校名不对,无权限查看!')
    }
  } else {
    next()
  }
})

// 💖💖💖全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
  console.log('后置路由守卫', to, from)
  document.title = to.meta.title || '硅谷系统'
})

// 导出路由器
export default router

35.2.5 独享路由守卫

src/router/index.js

js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'


//创建一个路由器
const router = new VueRouter({
  routes: [
    {
      name: 'guanyv',
      path: '/about',
      component: About,
      meta: { title: '关于' }
    },
    {
      name: 'zhuye',
      path: '/home',
      component: Home,
      meta: { title: '主页' },
      children: [
        {
          name: 'xinwen',
          path: 'news',
          component: News,
          meta: { title: '新闻' },
          // 💖💖💖独享守卫,特定路由切换之后被调用
          beforeEnter(to, from, next) {
            console.log('独享路由守卫', to, from)
            if (localStorage.getItem('school') === 'atguigu') {
              next()
            } else {
              alert('暂无权限查看')
            }
          }
        },
        {
          name: 'xiaoxi',
          path: 'message',
          component: Message,
          meta: { title: '消息' },
          children: [
            {
              name: 'xiangqing',
              path: 'detail',
              component: Detail,
              meta: { title: '详情' },
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title,
                }
              }
            }
          ]
        }
      ]
    }
  ]
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
  console.log('后置路由守卫', to, from)
  document.title = to.meta.title || '硅谷系统'
})

//导出路由器
export default router

35.2.6 组件内路由守卫

src/pages/About.vue

vue
<template>
    <h2>我是About组件的内容</h2>
</template>

<script>
    export default {
        name:'About',
        // 通过路由规则,离开该组件时被调用
        beforeRouteEnter (to, from, next) {
            console.log('About--beforeRouteEnter',to,from)
            if(localStorage.getItem('school')==='atguigu'){
                next()
            }else{
                alert('学校名不对,无权限查看!')
            }
        },
        // 通过路由规则,离开该组件时被调用
        beforeRouteLeave (to, from, next) {
            console.log('About--beforeRouteLeave',to,from)
            next()
        }
    }
</script>

35.3 路由器的两种工作模式

  1. 对于一个 url 来说,什么是 hash 值 ?

    # 及后面的内容就是 hash

  2. hash值 不会包括在 http 请求中,即:hash值 不会带给服务器

  3. hash 模式

    • 地址永远带着 #,不美观
    • 若以后地址通过第三方手机 app 分享,若 app 校验较严格,则地址会被标记为不合法
    • 兼容性较好
  4. history 模式

    • 地址干净,美观

    • 兼容性略比 hash 模式差

    • 应用部署上线需要后端人员的支持,解决刷新页面服务端 404 的问题

js
const router =  new VueRouter({
    // 💖💖💖 
	mode:'history',
	routes:[...]
})

export default router

Powered by VitePress & Vue 3