vue3 路由
完整的代码, 可以复制引用
vue-router库的相关功能
// 导入vue-router库的相关功能 import { createRouter, createWebHistory } from "vue-router"; // 导入Vuex store import store from "../store/index"; // 创建一个新的路由实例 const router = createRouter({ // 使用HTML5的History模式(这会消除URL中的#) history: createWebHistory(), // 定义路由规则 routes: [ { // 当URL为'/'时,加载Index页面,并设置keepAlive为true(这意味着此组件会被保持在内存中,不会重新渲染) path: '/', name: 'index', component: () => import('../pages/index'), meta: {keepAlive: true} }, { // 捕获所有未定义的路由,并重定向到首页 path: "/:catchAll(.*)", redirect: '/' } ] }) // 添加一个全局的导航守卫 router.beforeEach((to, from, next) => { // 获取即将要进入的路由对象的路径 let path = to.path; // 从Vuex store中获取URL历史数组 let arr = store.state.urlHistory; // 检查即将进入的路由路径是否已经存在于URL历史数组中 if(arr.includes(path)) { // 如果存在,则找到它的索引位置 let index = arr.findIndex((i) => path === i); // 从URL历史数组中删除这个路由路径 arr.splice(index, 1) // 并将其添加到数组的末尾(这样我们可以保持URL历史的顺序) arr.push(path) } else { // 如果即将进入的路由路径不在URL历史数组中,则直接将其添加到数组的末尾 arr.push(path); } // 继续执行路由导航 next(); }) export default router;