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;
相关推荐
NiceCloud喜云6 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby7 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing7 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩7 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车7 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思8 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫10 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。10 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星11 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒11 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端