提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Vue Router
Vue Router 是 Vue 官方的客户端路由解决方案。
客户端路由的作用是在单页应用 (SPA) 中将浏览器的 URL 和用户看到的内容绑定起来。当用户在应用中浏览不同页面时,URL 会随之更新,但页面不需要从服务器重新加载。
Vue Router 基于 Vue 的组件系统构建,你可以通过配置路由来告诉 Vue Router 为每个 URL 路径显示哪些组件
二、使用 Vue-Router
npm create vue@latest
- 创建路由表,404 页面捕获
import {
createRouter,
createWebHashHistory,
createWebHistory
} from 'vue-router'
import Admin from "~/layouts/admin.vue";
import Index from '~/pages/index.vue'
// 默认路由,所有用户共享
const routes = [
{
path: "/",
name:"admin",
component: Admin,
},
{
path: "/login",
component: Login,
meta: {
title: "登录页"
}
},
// 配置404页面
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: NotFound
}
]
// 动态路由,用于匹配菜单动态添加路由
const asyncRoutes = [{
path:"/",
name:"/",
component:Index,
meta:{
title:"后台首页"
}
},{
path:"/goods/list",
name:"/goods/list",
component:GoodList,
meta:{
title:"商品管理"
}
},{
path:"/category/list",
name:"/category/list",
component:CategoryList,
meta:{
title:"分类列表"
}
},{
path:"/user/list",
name:"/user/list",
component:UserList,
meta:{
title:"用户列表"
}
},{
path:"/order/list",
name:"/order/list",
component:OrderList,
meta:{
title:"订单列表"
}
}
}]
export const router = createRouter({
history: createWebHashHistory(),
routes
})
// 动态添加路由的方法
export function addRoutes(menus){
// 是否有新的路由
let hasNewRoutes = false
const findAndAddRoutesByMenus = (arr) =>{
arr.forEach(e=>{
let item = asyncRoutes.find(o=>o.path == e.frontpath)
if(item && !router.hasRoute(item.path)){
router.addRoute("admin",item)
hasNewRoutes = true
}
if(e.child && e.child.length > 0){
findAndAddRoutesByMenus(e.child)
}
})
}
findAndAddRoutesByMenus(menus)
return hasNewRoutes
}
// main.js 里挂载
import { router } from './router'
const app = createApp(App)
app.use(router)
三、全局路由守卫
- 创建一个新的 js 文件,并引入 router 路由表
import { addRoutes, router } from "~/router";
import { getToken } from "~/composables/auth";
import store from "./store";
// 全局前置守卫
let hasGetInfo = false;
router.beforeEach(async (to, from, next) => {
const token = getToken();
// 没有登录,强制跳转回登录页
if (!token && to.path != "/login") {
toast("请先登录", "error");
return next({ path: "/login" });
}
// 防止重复登录
if (token && to.path == "/login") {
toast("请勿重复登录", "error");
return next({ path: from.path ? from.path : "/" });
}
// 如果用户登录了,自动获取用户信息,并存储在vuex当中
let hasNewRoutes = false;
if (token && !hasGetInfo) {
let { menus } = await store.dispatch("getinfo");
hasGetInfo = true;
// 动态添加路由
hasNewRoutes = addRoutes(menus);
}
// 设置页面标题
let title = (to.meta.title ? to.meta.title : "") + "-帝莎编程商城后台";
document.title = title;
hasNewRoutes ? next(to.fullPath) : next();
});
// 全局后置守卫
router.afterEach((to, from) => );