router.ts
import { createRouter, createWebHistory } from "vue-router";
import { AppRoutes } from './route';
import { beforeEach, afterEach } from './guards.ts'
export const AppRouter = createRouter({
history: createWebHistory(),
routes: AppRoutes,
scrollBehavior: () => ({ top: 0 })
})
AppRouter.beforeEach(beforeEach);//路由守卫
AppRouter.afterEach(afterEach);
from
: 表示当前所在的路由对象。savedPosition
: 表示滚动位置的历史记录。
scrollBehavior 是一个函数,它会在路由导航时被调用,它接收三个参数:具体来说,scrollBehavior 是一个函数,它会在路由导航时被调用,它接收三个参数:to
: 表示要跳转到的目标路由对象。
函数的返回值会决定页面切换时的滚动行为:
- 如果返回一个位置对象,会以
x
和y
的方式指定滚动位置。 - 如果返回一个选择器字符串,会滚动到匹配该选择器的元素。
- 如果返回
false
,则不会进行滚动。
在这段代码中,scrollBehavior
被设置为一个箭头函数 () => ({ top: 0 })
,这意味着无论导航到哪个路由,页面都会在顶部开始滚动(top: 0
)。
route.ts
import { markRaw } from 'vue'
import Home from "../views/Home.vue";
export const AppRoutes = markRaw([
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/login",
name: "Login",
component: () =>
import(/* webpackChunkName: "about" */ "../views/login.vue")
},
{
path: "/system",
name: "System",
component: () =>
import(/* webpackChunkName: "system" */ "../views/system/System.vue"),
children: [
{
path: "role",
name: '角色管理',
component: () =>
import(/* webpackChunkName: "system" */ "../views/system/modules/role/SystemRole.vue"),
},
{
path: "user",
name: '用户管理',
component: () =>
import(/* webpackChunkName: "system" */ "../views/system/modules/user/SystemUser.vue"),
}
]
},
])
guards.ts
import {
useGlobalUserStore
} from '@/store/UserGlobalStore.ts';
import {
useGlobalStore
} from '@/store/MenuGlobalStore.ts';
import { ElMessage } from 'element-plus'
export async function beforeEach(to) {
//如果当前页面是登录页面,把title修改一下
if (to.path == '/login') {
document.title = '办鹿后台管理系统';
return;
}
//如果进入某一个页面获取不到token,那么就跳转到登录页
if (!localStorage.getItem('token')) {
return '/login'
}
//如果可以获取用户信息,就证明用户的token一定正确
try {
//拿到用户信息的数据
const store = useGlobalUserStore();
await store.initUserInfoAndConfig();
// 刚刚是最高权限
const { permissions } = store;
if (permissions[0] === "*:*:*") {
return true;
}
let { authSlideMenuMap } = useGlobalStore();
if (!authSlideMenuMap.get(to.path)) {
ElMessage.error('抱歉,您没有该权限')
return false
}
// 判断该用户是否有本权限的路由
useGlobalStore
} catch (e) {
return '/login'
}
}
export const afterEach = async (to, from, next) => {
}
相关作者
- 获取点赞0
- 文章阅读量264
评论()