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;
相关推荐
灵感__idea1 小时前
JavaScript高级程序设计(第5版):好的编程就是掌控感
前端·javascript·程序员
烛阴2 小时前
Mix
前端·webgl
代码续发2 小时前
前端组件梳理
前端
试图让你心动3 小时前
原生input添加删除图标类似vue里面移入显示删除[jquery]
前端·vue.js·jquery
_Kayo_3 小时前
VUE2 学习笔记6 vue数据监测原理
vue.js·笔记·学习
陈不知代码4 小时前
uniapp创建vue3+ts+pinia+sass项目
前端·uni-app·sass
小王码农记4 小时前
sass中@mixin与 @include
前端·sass
陈琦鹏4 小时前
轻松管理 WebSocket 连接!easy-websocket-client
前端·vue.js·websocket
hui函数4 小时前
掌握JavaScript函数封装与作用域
前端·javascript
行板Andante4 小时前
前端设计中如何在鼠标悬浮时同步修改块内样式
前端