首页  >  问答  >  正文

Vue 3 + Vite 开发服务器中的动态路由导致页面重新加载时出现 404 错误

在我的项目中我使用 Vue 3.2.36 + Vite 2.9.9 + VueRouter 4.1.3

我使用 npm run dev 运行开发服务器。

我的路线定义:

routes: [
    {
      path: '/',
      component: Home,
    },
    {
      path: '/about',
      component: () => import('@/views/About.vue'),
    },
    {
      path: '/user-details/:login',
      name: 'userDetails',
      component: () => import('@/views/User.vue'),
    },
    {
      path: '/:pathMatch(.*)*',
      component: NotFound,
    }
  ],

当我使用 router.push({name: 'userDetails', params: {login: 'john.smith'}}) 以编程方式导航时,userDetails 页面/组件正确显示。

但是如果我浏览器重新加载开发服务器返回 404 并且 NotFound 组件不会显示。

Chrome:


FF:


工作示例:此处

我已将问题隔离给Vite。使用 Vue CLI 一切正常。

我的vite.config.js

import loadVersion from 'vite-plugin-package-version';

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig(() => {
  return {
    server: {
      port: 8080,
    },
    plugins: [vue(), loadVersion()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    envDir: './src/configuration',
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/scss/_variables.scss";',
        },
      },
    },
  };
});

检查了我的index.html


检查了 vue-router 历史模式文档,并在警告部分中指出,如果未找到路由,路由器应默认为 index.html ,并且它使用 Vue CLI 执行此操作,但不使用 Vite 执行此操作。

P粉811329034P粉811329034328 天前856

全部回复(2)我来回复

  • P粉757556355

    P粉7575563552023-10-28 00:56:43

    我的 Web 应用程序位于 Azure DevOps 上,但位于 Linux 上 对于 Linux Web 应用程序,您必须添加下一个命令才能在启动时运行 Web 应用程序命令。这对我有用。

    pm2 serve /home/site/wwwroot --no-daemon --spa

    您可以在本文中查看更多内容 Azure webapp linux 上的 React 应用

    回复
    0
  • P粉011684326

    P粉0116843262023-10-28 00:30:48

    是的,它知道 Vite 中的bug
    解决方案是在 Vite 中使用 插件,如所述 此处

    对我来说,这是不行的。我要切换到 Vue CLI。
    不想和这种小妖精打交道。
    几年后我会再次访问 Vite。

    回复
    0
  • 取消回复