Ithy Logo

Vite + Vue 3 + Router 新手教程

快速构建现代化前端项目的完整指南

modern front end development

关键要点

  • 快速项目初始化: 使用 Vite 工具快速搭建 Vue 3 项目框架。
  • 路由配置: 集成 Vue Router 4,实现页面间的高效导航。
  • 优化开发体验: 配置别名、全局样式及开发环境,提升开发效率。

1. 环境准备

步骤 1. 安装 Node.js 和 npm

在开始之前,确保您的开发环境中安装了最新版本的 Node.jsnpm。推荐 Node.js 版本 ≥ 14.18+。

  • 访问 Node.js 官网,下载并安装适合您系统的版本。
  • 安装完成后,打开终端(或命令提示符),输入以下命令以验证安装是否成功:
node -v
npm -v

您应该能够看到 Node.js 和 npm 的版本号输出。

步骤 2. 安装 Vite

Vite 是一个由 Vue.js 核心团队开发的前端构建工具,具有极速的冷启动和热模块替换 (HMR) 性能。

全局安装 Vite(可选):

npm install -g create-vite

或者,您可以在创建项目时直接使用 npx。


2. 创建 Vite + Vue 3 项目

步骤 1. 初始化项目

使用 Vite 快速创建一个 Vue 3 项目。

npm create vite@latest my-vue-app -- --template vue

在上面的命令中,my-vue-app 是您的项目名称,可以根据需要更改。

步骤 2. 安装依赖

进入项目目录并安装所需的依赖包。


cd my-vue-app
npm install

步骤 3. 运行开发服务器

启动开发服务器,确保一切正常。

npm run dev

打开浏览器访问 http://localhost:5173,您将看到 Vue 3 的欢迎页面。


3. 安装和配置 Vue Router

步骤 1. 安装 Vue Router

Vue Router 是 Vue.js 官方的路由管理器,用于构建单页应用 (SPA)。安装 Vue Router 4 版本,它与 Vue 3 兼容。

npm install vue-router@4

步骤 2. 设置路由配置文件

src 目录下创建一个 router 文件夹,并在其中新增 index.js 文件:


mkdir src/router
touch src/router/index.js

编辑 src/router/index.js,配置路由:

import { createRouter, createWebHistory } from 'vue-router'

// 路由表
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue') // 懒加载组件
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/views/About.vue') // 懒加载组件
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

步骤 3. 配置路由入口

打开 src/main.js,导入并使用路由器:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

步骤 4. 更新 App.vue

App.vue 中添加导航链接和路由视图:

<template>
  <div>
    <nav>
      <router-link to="/">首页</router-link> |
      <router-link to="/about">关于</router-link>
    </nav>
    <router-view />
  </div>
</template>

<script setup>
import { RouterLink, RouterView } from 'vue-router'
</script>

<style scoped>
nav {
  padding: 1em;
  background-color: #f0f0f0;
}
nav a {
  margin: 0 0.5em;
  text-decoration: none;
  color: #42b983;
}
</style>

步骤 5. 创建视图组件

src/views 目录下创建 Home.vueAbout.vue


mkdir src/views
touch src/views/Home.vue
touch src/views/About.vue

Home.vue:

<template>
  <div class="home">
    <h1>首页</h1>
    <p>欢迎来到首页!</p>
  </div>
</template>

<script setup>
// 无需额外脚本
</script>

<style scoped>
.home {
  padding: 2em;
}
</style>

About.vue:

<template>
  <div class="about">
    <h1>关于我们</h1>
    <p>这里是关于页面的内容。</p>
  </div>
</template>

<script setup>
// 无需额外脚本
</script>

<style scoped>
.about {
  padding: 2em;
}
</style>

4. 优化开发体验

步骤 1. 配置路径别名

为了简化模块导入路径,可以配置路径别名。例如,使用 @ 代表 src 目录:

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
})

保存配置后,您可以在代码中使用别名,例如:

import Home from '@/views/Home.vue'

步骤 2. 添加全局样式

为整个项目添加公共样式,方便后续开发:

  1. 创建全局样式文件:
mkdir src/assets/styles
touch src/assets/styles/global.css

src/assets/styles/global.css 中添加一些基础样式:

body {
  margin: 0;
  font-family: Arial, sans-serif;
  background-color: #fafafa;
}

a {
  color: #42b983;
}

h1, h2, h3, h4, h5, h6 {
  color: #333;
}

src/main.js 中引入全局样式:

import './assets/styles/global.css'

步骤 3. 配置开发服务器(可选)

可以根据需要配置开发服务器,例如修改端口号、开启 HTTPS 等:

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  server: {
    port: 3000, // 修改默认端口为 3000
    open: true, // 自动打开浏览器
    https: false // 关闭 HTTPS
  }
})

5. 项目结构与最佳实践

推荐的项目结构

保持项目结构清晰有助于维护和扩展。以下是一个推荐的项目结构:

目录/文件 描述
src/ 项目的源代码目录
src/assets/ 存放静态资源,如图片、样式等
src/components/ 可复用的 Vue 组件
src/router/ 路由配置文件夹
src/views/ 页面级组件
src/store/ 状态管理(如使用 Vuex 或 Pinia)
src/main.js 应用入口文件
src/App.vue 根组件

代码风格与规范

遵循一致的代码风格有助于团队协作和代码可读性。建议使用以下工具和配置:

  • ESLint: 用于 JavaScript 和 Vue 代码的静态分析。
  • Prettier: 代码格式化工具,确保代码风格一致。
  • EditorConfig: 统一不同编辑器的配置。

安装 ESLint 和 Prettier:

npm install eslint prettier eslint-plugin-vue eslint-config-prettier --save-dev

创建或更新配置文件,如 .eslintrc.js.prettierrc,根据项目需求进行配置。


6. 运行和测试项目

启动开发服务器

确保所有配置正确后,启动开发服务器并测试项目:

npm run dev

打开浏览器访问 http://localhost:5173,您应该能够看到首页,并通过导航链接访问关于页面。

常见问题排查

在开发过程中,可能会遇到一些常见问题。以下是一些排查建议:

  • 模块找不到: 检查路径是否正确,尤其是在配置别名后。
  • 路由无法跳转: 确认 Vue Router 是否正确安装并在 main.js 中正确使用。
  • 热更新失效: 尝试重启开发服务器,或检查是否有错误日志。

7. 扩展与优化

添加更多页面和路由

在项目中添加更多页面,可以通过以下步骤实现:

  1. src/views 目录下创建新的 Vue 组件,例如 Contact.vue
  2. src/router/index.js 中添加新的路由配置:
{
  path: '/contact',
  name: 'Contact',
  component: () => import('@/views/Contact.vue')
}

将路由链接添加到导航栏:

<router-link to="/contact">联系</router-link>

集成状态管理(如 Pinia)

为了管理复杂的应用状态,可以引入状态管理库,如 Pinia

安装 Pinia:

npm install pinia

src/main.js 中集成 Pinia:

import { createPinia } from 'pinia'

const pinia = createPinia()
app.use(pinia)

创建和使用 Pinia store:

// src/store/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})
<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <button @click="counter.increment">增加</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/store/counter'
const counter = useCounterStore()
</script>

添加样式框架(如 Element Plus)

为了快速构建美观的用户界面,可以集成 UI 组件库,如 Element Plus

安装 Element Plus:

npm install element-plus

src/main.js 中导入和使用 Element Plus:

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

app.use(ElementPlus)

在组件中使用 Element Plus 组件:

<template>
  <el-button type="primary">按钮</el-button>
</template>

结论

通过本教程,您已经掌握了如何使用 Vite 快速搭建一个基于 Vue 3 的前端项目,并集成 Vue Router 实现路由管理。同时,通过配置路径别名、全局样式以及集成状态管理和 UI 组件库,您可以进一步优化开发体验和项目结构。随着项目的不断发展,您可以根据需求添加更多功能,提升应用的复杂度和用户体验。

参考资料


Last updated January 21, 2025
Ask me more