Vue 3 项目搭建
Vue 3 是当前 Vue 新项目的默认选择,推荐配合 Vite、TypeScript、Pinia 和 Vue Router 使用。它提供更好的类型推导、组合式逻辑复用和构建体验。
环境要求
建议使用当前 LTS 版本的 Node.js。创建项目前先确认版本:
bash
node -v
npm -v如果团队协作,建议在项目中声明 Node 版本,例如 .nvmrc 或 package.json 的 engines 字段。
使用 create-vue
官方推荐使用 create-vue 创建 Vue 3 项目:
bash
npm create vue@latest
cd your-project
npm install
npm run dev交互式选项建议:
- TypeScript:中长期项目建议开启。
- JSX:只有明确需要时开启。
- Vue Router:多页面应用开启。
- Pinia:存在跨页面状态时开启。
- Vitest:有单元测试要求时开启。
- ESLint/Prettier:团队项目建议开启。
使用 Vite 模板
如果只需要最小 Vue 模板,可以使用 Vite:
bash
npm create vite@latest my-vue-app -- --template vuebash
pnpm create vite my-vue-app --template vuebash
yarn create vite my-vue-app --template vueTypeScript 模板:
bash
npm create vite@latest my-vue-app -- --template vue-ts推荐目录结构
text
src/
api/ # 请求封装和接口函数
assets/ # 静态资源
components/ # 通用组件
composables/ # 组合式函数
layouts/ # 布局组件
router/ # 路由
stores/ # Pinia store
styles/ # 全局样式
types/ # 全局类型
utils/ # 工具函数
views/ # 页面组件组合式 API 示例
把可复用逻辑放到 composables 中:
ts
// src/composables/useLoading.ts
import { ref } from "vue";
export function useLoading() {
const loading = ref(false);
async function run<T>(task: () => Promise<T>) {
loading.value = true;
try {
return await task();
} finally {
loading.value = false;
}
}
return { loading, run };
}页面中使用:
vue
<script setup lang="ts">
import { useLoading } from "@/composables/useLoading";
const { loading, run } = useLoading();
function submit() {
run(async () => {
// submit form
});
}
</script>Vite 别名配置
ts
// vite.config.ts
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url))
}
}
});TypeScript 同步配置:
json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}状态管理建议
Pinia 适合存放跨页面共享状态,例如用户信息、权限、主题、购物车等。局部页面状态优先放在组件或 composable 中,不要全部塞进全局 store。
ts
import { defineStore } from "pinia";
export const useUserStore = defineStore("user", {
state: () => ({
token: "",
profile: null as null | { id: number; name: string }
}),
actions: {
setToken(token: string) {
this.token = token;
}
}
});开发规范
- 组件使用
script setup,复杂组件再拆分 composable。 - props 和 emits 明确定义类型。
- 页面组件负责业务编排,通用组件避免耦合接口请求。
- 路由懒加载,降低首屏包体积。
- 对复杂表单、权限和关键流程补充测试。
常用命令
bash
npm run dev
npm run build
npm run preview