怎么开发一个Vue3项目

开发一个 Vue 3 项目,现在最主流的做法是:

Vue 3 + Vite + TypeScript + Vue Router + Pinia + Axios + UI 组件库

下面按从零到上线的流程走一遍。


一、准备环境

先装好:

  • Node.js 18+(推荐 20+)
  • 包管理器:npm / pnpm / yarn

检查:

bash 复制代码
node -v
npm -v

二、创建项目

用 Vite 创建 Vue 3 项目:

bash 复制代码
npm create vite@latest my-vue3 -- --template vue-ts

如果不用 TypeScript:

bash 复制代码
npm create vite@latest my-vue3 -- --template vue

进入目录并安装依赖:

bash 复制代码
cd my-vue3
npm install
npm run dev

浏览器打开 http://localhost:5173,能看到页面就成功了。


三、安装常用依赖

一个完整项目通常还需要:

bash 复制代码
npm install vue-router@4 pinia axios element-plus
npm install -D sass
  • vue-router:路由
  • pinia:状态管理
  • axios:请求后端
  • element-plus:UI 组件库
  • sass:写样式

四、项目目录结构

推荐这样组织:

text 复制代码
src/
├── api/            # 接口封装
├── assets/         # 静态资源
├── components/     # 公共组件
├── layouts/        # 布局
├── router/         # 路由
├── stores/         # Pinia 状态
├── styles/         # 全局样式
├── utils/          # 工具函数
├── views/          # 页面
├── App.vue
└── main.ts

五、配置入口文件

1. src/main.ts

ts 复制代码
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
import './styles/index.scss'

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

app.mount('#app')

2. src/App.vue

vue 复制代码
<template>
  <router-view />
</template>

六、配置路由

新建 src/router/index.ts:

ts 复制代码
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/HomeView.vue')
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('@/views/AboutView.vue')
    }
  ]
})

export default router

为了让 @ 指向 src,在 vite.config.ts 中配置:

ts 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

同时在 tsconfig.json 中加:

json 复制代码
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

七、写一个 Vue 3 页面

src/views/HomeView.vue:

vue 复制代码
<template>
  <div class="home">
    <h1>{{ title }}</h1>
    <el-button type="primary" @click="count++">
      点击次数:{{ count }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const title = ref('Vue3 项目')
const count = ref(0)
</script>

<style scoped lang="scss">
.home {
  padding: 20px;
  text-align: center;
}
</style>

Vue 3 推荐使用:

  • <script setup>
  • ref / reactive
  • computed / watch
  • 生命周期钩子

八、状态管理 Pinia

新建 src/stores/user.ts:

ts 复制代码
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const name = ref('')

  function setToken(val: string) {
    token.value = val
  }

  function logout() {
    token.value = ''
    name.value = ''
  }

  return { token, name, setToken, logout }
})

页面中使用:

vue 复制代码
<script setup lang="ts">
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
</script>

九、封装 Axios 请求

新建 src/utils/request.ts:

ts 复制代码
import axios from 'axios'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000
})

request.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

request.interceptors.response.use(
  res => res.data,
  err => {
    console.error(err)
    return Promise.reject(err)
  }
)

export default request

新建 src/api/user.ts:

ts 复制代码
import request from '@/utils/request'

export function login(data: { username: string; password: string }) {
  return request.post('/login', data)
}

十、环境变量

根目录创建:

.env.development

env 复制代码
VITE_API_BASE_URL=/api

.env.production

env 复制代码
VITE_API_BASE_URL=https://api.example.com

代码中通过:

ts 复制代码
import.meta.env.VITE_API_BASE_URL

十一、开发调试

启动开发服务器:

bash 复制代码
npm run dev

常用调试方式:

  • Chrome DevTools
  • Vue Devtools 浏览器插件
  • 真机调试
  • vConsole(移动端)

十二、构建与部署

构建:

bash 复制代码
npm run build

生成 dist 目录,部署到 Nginx:

nginx 复制代码
server {
  listen 80;
  root /var/www/my-vue3/dist;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }

  location /api/ {
    proxy_pass http://127.0.0.1:3000;
  }
}

也可以用 Vercel、Netlify、Docker 部署。


十三、推荐最佳实践

  1. 统一用 <script setup>,代码更简洁。
  2. 按功能拆目录:api、views、components、stores。
  3. 路由懒加载 :() => import('@/views/xxx.vue')。
  4. 请求统一封装:拦截器处理 Token、错误。
  5. 环境变量区分开发和生产。
  6. 配置 ESLint + Prettier 统一代码风格。
  7. 使用 TypeScript 减少类型错误。
  8. UI 库按需引入,减小打包体积。
  9. 接口和页面分离,方便维护。
  10. 上线前做性能优化:图片压缩、代码分割、CDN。

十四、最小完整流程

bash 复制代码
# 1. 创建项目
npm create vite@latest my-vue3 -- --template vue-ts
cd my-vue3

# 2. 安装依赖
npm install
npm install vue-router@4 pinia axios element-plus
npm install -D sass

# 3. 启动
npm run dev

# 4. 构建
npm run build

然后按上面步骤配置:

  1. main.ts 挂载 Pinia、Router、Element Plus
  2. 建 router/index.ts
  3. 建 stores/
  4. 建 utils/request.ts
  5. 写 views/ 页面
  6. 配置 vite.config.ts 别名
  7. 部署 dist

如果你要做的具体是后台管理系统 还是移动端 H5,技术栈会略有不同:后台常用 Element Plus,H5 常用 Vant。你可以告诉我项目类型,我可以给你一套更具体的目录和代码模板。

相关推荐
庖丁解牛1 小时前
第二课:把代码保存成网页 + 认识变量 (2)
前端
梦里寻码1 小时前
从 0 到 1 用 NestJS + LangChain 搭一套可售卖的 SaaS AI 客服:挂件一行代码接入,知识库秒变 SEO 帮助中心
前端·后端·github
爱喝水的小周1 小时前
实验十一 Vuex 实现王者荣耀后台比赛管理系统
前端·css·html
三十而立洋1 小时前
前端模块化的演进:从全局变量到 Import Maps
前端·javascript·前端工程化
橘猫走江湖1 小时前
浮动塌陷复现失败:父元素为什么一直不塌
前端·css
用户1733598075371 小时前
纯前端 PDF 按书签拆分避坑指南:拆分后章节对不上?
前端·javascript·vue.js
мо仙堡杠把子ご灬1 小时前
Flex 自适应布局:告别 calc,用一个 height-auto 搞定
前端·javascript
环境栈笔记1 小时前
指纹浏览器检查代理失败怎么排查?先分清代理、网络和检测服务
前端·人工智能·后端·自动化
ShineWinsu2 小时前
对于HTML:HTML常见标签的解析—下
前端·css·面试·html·标签·表单·emmet