首頁  >  問答  >  主體

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粉811329034329 天前862

全部回覆(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
  • 取消回覆