使用create-vue@3创建项目时Vue Router无法加载的问题
Vue Router在create-vue@3项目中无法正常加载的问题
我尝试使用Vue Router,CDN方式在单个HTML文件中可正常运行,但通过create-vue@3创建的项目却无法正常加载路由。
复现步骤
- 执行命令
npm create vue@3 - 配置选项:
- 项目名称:vue-project
- 添加TypeScript:是
- 添加JSX支持:是
- 添加Vue Router用于单页应用开发:是
- 添加Pinia状态管理:否
- 添加Vitest单元测试:否
- 添加端到端测试方案:否
- 添加ESLint代码质量检查:否
- 安装所有依赖
- 修改
src/main.ts为如下内容:
import * as Vue from 'vue' import * as VueRouter from 'vue-router' // 1. 定义路由组件 // 也可以从其他文件导入 const Home = { template: '<div>Home</div>' } const About = { template: '<div>About</div>' } // 2. 定义路由规则 // 每个路由映射到一个组件,后续再讨论嵌套路由 const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, // { path: '/smm', component: About }, ] // 3. 创建路由实例并传入`routes`配置 // 这里可以传入额外配置,先保持简单 const router = VueRouter.createRouter({ // 4. 指定路由模式,这里用hash模式简化配置 history: VueRouter.createWebHashHistory(), routes, // 等同于`routes: routes` }) // 5. 创建并挂载根实例 const app = Vue.createApp({}) // 必须调用use(router)让整个应用启用路由 app.use(router) app.mount('#app')
- 修改
index.html为如下内容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/favicon.ico"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vite App</title> </head> <body> <div id="app"> <h1>Hello App!</h1> <p> <!-- 使用router-link组件进行导航 --> <!-- 通过`to`属性指定目标路由 --> <!-- `<router-link>`会渲染成带有正确`href`属性的`<a>`标签 --> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <!-- 路由出口 --> <!-- 匹配到的路由组件将在这里渲染 --> <router-view></router-view> </div> <script type="module" src="/src/main.ts"></script> </body> </html>
- 执行命令
yarn start
相关版本
"dependencies": { "vue": "^3.3.2", "vue-router": "^4.2.0" },
问题原因及解决方案
核心问题是混淆了CDN模式与Vite项目的结构逻辑:
Vite项目中不能直接修改
index.html的#app内容
create-vue创建的项目里,#app是Vue根组件的挂载点,所有页面内容需通过Vue组件(如App.vue)管理,而非直接写在静态index.html中。直接在index.html里写router-link和router-view,Vue无法识别并处理这些自定义组件。正确调整步骤
- 恢复
index.html默认内容,仅保留<div id="app"></div>,删除其中的导航和路由出口代码。 - 修改
src/App.vue,将导航和路由出口移至此处:
<template> <h1>Hello App!</h1> <p> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <router-view></router-view> </template>
- 可简化
src/main.ts的导入方式(可选):
import { createApp } from 'vue' import { createRouter, createWebHashHistory } from 'vue-router' const Home = { template: '<div>Home</div>' } const About = { template: '<div>About</div>' } const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] const router = createRouter({ history: createWebHashHistory(), routes, }) createApp({}) .use(router) .mount('#app')
调整后路由即可正常工作,因为Vite+Vue项目要求所有Vue相关组件都通过组件系统管理,才能被Vue正确解析和渲染。
内容的提问来源于stack exchange,提问作者Flecart
相关产品推荐
相关产品推荐

