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;
相关推荐
老前端的功夫11 小时前
Vue 3 性能深度解析:从架构革新到运行时的全面优化
javascript·vue.js·架构
天天扭码11 小时前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子12 小时前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing13 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼13 小时前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长14 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs14 小时前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队14 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程
m0_4711996314 小时前
【场景】前端怎么解决离线收银、数据同步异常等场景问题
前端·javascript