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;
相关推荐
Filotimo_11 小时前
2.CSS3.(2).html
前端·css
yinuo12 小时前
uniapp微信小程序华为鸿蒙定时器熄屏停止
前端
gnip13 小时前
vite中自动根据约定目录生成路由配置
前端·javascript
前端橙一陈14 小时前
LocalStorage Token vs HttpOnly Cookie 认证方案
前端·spring boot
~无忧花开~14 小时前
JavaScript学习笔记(十五):ES6模板字符串使用指南
开发语言·前端·javascript·vue.js·学习·es6·js
泰迪智能科技0115 小时前
图书推荐丨Web数据可视化(ECharts 5)(微课版)
前端·信息可视化·echarts
CodeCraft Studio15 小时前
借助Aspose.Email,使用 Python 读取 Outlook MSG 文件
前端·python·outlook·aspose·email·msg·python读取msg文件
家里有只小肥猫16 小时前
react 初体验2
前端·react.js·前端框架
慧慧吖@17 小时前
前端发送请求时,参数的传递格式
前端
L李什么李17 小时前
HTML——使用表格制作简历
前端·javascript·html