详见:全局前置守卫网址
使用场景:
全局前置守卫的原理:
全局前置守卫是一种路由守卫,它在路由被访问之前进行拦截。它允许我们在路由被访问之前进行一些处理,例如权限验证、请求参数预处理等。在Vue Router中,我们可以通过在路由配置中添加beforeEnter守卫来实现全局前置守卫。
在 src/router/index.js 文件夹中 添加配置:
// 创建一个数组用来存放,需要用户登录的页面路径
const authUrl = ['/pay', '/myorder']
// 创建全局前置守卫
router.beforeEach((to, from, next) => {
// 判断是否为权限页面
if (!authUrl.includes(to.path)) { // 非权限页面直接放行
next()
} else {
const token = store.getters.token
// console.log(token)
if (token) {
next()
} else {
next('/login')
}
}
})
注:
- to 往哪里去, 到哪去的路由信息对象
- from 从哪里来, 从哪来的路由信息对象
- next() 是否放行
- 如果next()调用,就是放行
- next(路径) 拦截到某个路径页面
完整代码:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/layout/home'
import User from '@/views/layout/user'
import Cart from '@/views/layout/cart'
import Category from '@/views/layout/category'
import store from '@/store'
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const ProDetail = () => import('@/views/prodetail')
const Pay = () => import('@/views/pay')
const MyOrder = () => import('@/views/myorder')
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/',
component: Layout,
redirect: '/home',
children: [
{
path: '/home',
component: Home
},
{
path: '/user',
component: User
},
{
path: '/cart',
component: Cart
},
{
path: '/category',
component: Category
}
]
},
{
path: '/login',
component: Login
},
{
path: '/search',
component: Search
},
{
path: '/searchlist',
component: SearchList
},
{
path: '/prodetail/:id',
component: ProDetail
},
{
path: '/pay',
component: Pay
},
{
path: '/myorder',
component: MyOrder
}
]
})
// 创建一个数组用来存放,需要用户登录的页面路径
const authUrl = ['/pay', '/myorder']
// 创建全局前置守卫
router.beforeEach((to, from, next) => {
// 判断是否为权限页面
if (!authUrl.includes(to.path)) { // 非权限页面直接放行
next()
} else {
const token = store.getters.token
// console.log(token)
if (token) {
next()
} else {
next('/login')
}
}
})
export default router