导航守卫可以控制路由的访问权限。示意图如下:
全局前置守卫
每次发生路由的导航跳转时,都会触发全局前置守卫。因此,在全局前置守卫中,程序员可以对每个路由进行 访问权限的控制。
全局前置守卫的回调函数中接收 3 个形参,格式为:
//src/router/index.js 就是当前项目的路由模块
// 导入 Vue 和 VueRouter 的包
import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入需要的组件
import Home from '@/components/Home.vue'
import Movie from '@/components/Movie.vue'
import About from '@/components/About.vue'
import Tab1 from '@/components/tabs/Tab1.vue'
import Tab2 from '@/components/tabs/Tab2.vue'
// 调用 Vue.use() 函数,把 VueRouter 安装为 Vue 的插件
Vue.use(VueRouter)
// 创建路由的实例对象
const router = new VueRouter({
// routes 是一个数组,作用:定义 hash 地址与组件之间的对应关系
routes:[
{path:'/',redirect:'/home'},
{path:'/home',component:Home},
//为路由规则开启 props 传参,从而方便的拿到动态参数的值
{path:'/movie/:id',component:Movie,props:true},
{path:'/about',component:About,children:[
// 子路由规则
{path:'tab1',component:Tab1},
{path:'',component:Tab2}
]}
]
})
-----------------------------------------------------------------
// 为 router 实例对象,声明全局前置导航守卫
// 只要发生了路由的跳转,必然会触发 beforeEach 指定的 function 回调函数
router.beforeEach(function(to,from,next){
//next() 表示放行的意思
next()
})
-----------------------------------------------------------------
// 向外共享路由的实例对象
export default router
next 函数的 3 种调用方式
参考示意图,分析 next 函数的 3 种调用方式最终导致的结果:
-
当前用户拥有后台主页的访问权限,直接放行:next()
-
当前用户没有后台主页的访问权限,强制其跳转到登录页面:next('/login')
-
当前用户没有后台主页的访问权限,不允许跳转到后台主页:next(false)