vue-router路由问题:可以通过$router.push()跳转,但刷新后又变成空白页面

pageage.json

js 复制代码
"vue": "~3.1.5",
"vue-axios": "~3.2.4",
"vue-router": "~4.0.10",

代码没有问题,一直搞不懂为什么通过this.$router.push("/paper/detail")可以跳进去,但是进去之后再刷新就一直是空白页面,各种百度/问AI,要么说 把mode的问题,换成hash/history;要么说服务端配置问题(静态前端跟服务端有毛的关系);要么说需要路由嵌套(/paper的children里面写/detail,这2是同级的,又不是父嵌子)

最后终于意识到是publicPath: '/'的问题:

例如,在 vue.config.js 中:

js 复制代码
module.exports = {
  publicPath: '/' // 默认是'./'
}

或者在 webpack.config.js 中配置静态资源目录:

js 复制代码
output: {
  publicPath: '/static/',  // 根据需要修改路径
}

router.js

js 复制代码
import { createRouter, createWebHistory } from 'vue-router';
import EleLayout from '@/layout/index';
// 静态路由
const routes = [
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/exception/404')
  },
];
const mainRouter = [
  {
    path: "/index",
    component: () => import('@/views/index/index'),
    meta: { title: "主页", keepAlive: true }
  },
  {
    path: "/paper",
    component: () => import('@/views/paper/index'),
    meta: { title: "公文", keepAlive: true },
  },
  {
    path: "/paper/detail",
    component: () => import('@/views/paper/detail'),
    meta: { title: "公文", keepAlive: true }
  },
]

const router = createRouter({
  mode: 'history', // hash history
  routes,
  history: createWebHistory(),
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0, left: 0 };
    }
  }
});

router.beforeEach((to, from, next) => {
    // 将新的子路由添加到父路由中
    router.addRoute({
      path: '/',
      redirect: '/index',
      name: 'layout',
      component: EleLayout,
      children: mainRouter
    });    
    next({ ...to, replace: true });
});

export default router;
相关推荐
爱码小白21 分钟前
importlib模块
开发语言·前端·python
猫猫不是喵喵.1 小时前
Vue2 的 Vuex 状态管理与 Vue3 的 Pinia 状态管理
前端·javascript·vue.js
greenbbLV1 小时前
中小公司积分商城选型:SaaS与私有化方案对比解析
大数据·前端·小程序
看昭奚恤哭2 小时前
Flutter 布局核心思想
开发语言·javascript·flutter
朝阳5812 小时前
Cesium `Camera.flyTo`:“飞过去“
javascript
NutShell Wang2 小时前
Vite 8.1 深度拆解:Rolldown 统一打包器如何终结前端构建的「双引擎时代」
前端·rust·开源·vite·开发者工具·vibe coding
朱容zr3331332 小时前
请解释“回表”的概念。
java·前端·数据库
leslie1183 小时前
webpack笔记
前端·webpack
宁风NF3 小时前
JavaScript:内存、垃圾回收、性能优化
开发语言·前端·javascript·学习·性能优化·es6
勾勾圈圈蛋蛋3 小时前
DOM、BOM、DOM操作详解 + 结合Vue响应式关联梳理
前端