You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3项目构建后Vue Router无法正常工作问题求助

问题解决:Vue3构建后路由失效

核心原因

使用createWebHistory模式时,部署后的静态服务器无法识别/:shop_id这类动态路由,直接访问或刷新页面会返回404;同时你的路由配置没有根路径(/)的匹配规则,初始访问也可能出现异常。

解决方案

1. 调整路由配置

添加根路径重定向或兜底路由,确保所有请求都能匹配到对应页面:

// router/index.js
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        // 根路径重定向到默认shop_id,可根据业务调整默认值
        {
            path: "/",
            redirect: "/default-shop"
        },
        {
            path: "/:shop_id",
            name: "home",
            component: HomeView,
        },
        // 兜底路由,匹配所有未定义的路径
        {
            path: "/:pathMatch(.*)*",
            redirect: "/default-shop"
        }
    ],
});

export default router;

2. 配置服务器 fallback 规则

createWebHistory模式依赖服务器将所有路由请求转发到index.html,不同服务器配置方式如下:

  • Nginx:在站点配置中添加
    location / {
      try_files $uri $uri/ /index.html;
    }
    
  • Apache:创建.htaccess文件
    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
    </IfModule>
    
  • 本地测试:执行vite preview启动预览服务器,它会自动处理fallback规则,可快速验证构建包是否正常。

3. 检查BASE_URL配置

如果应用部署在子路径下(如https://xxx.com/my-app/),需要在vite.config.js中设置base:

// vite.config.js
export default defineConfig({
  base: '/my-app/', // 对应实际部署的子路径
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

根路径部署时无需修改,默认值为'/'。

验证步骤

  1. 重新执行npm run build构建项目
  2. 用vite preview本地测试路由是否正常
  3. 部署到服务器时确保已配置fallback规则

内容的提问来源于stack exchange,提问作者Md Mahfuzur Rahman Arif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:50:43