Vue3和Vite从零开始搭建项目的详细步骤
- 创业
- 2025-08-21 19:45:02

以下是使用 Vue 3 和 Vite 从零开始搭建项目的详细步骤:
一、环境准备
安装 Node.js (建议 v16+)
官网下载: nodejs.org
验证安装:
bash
复制
node -v npm -v二、创建 Vite 项目
使用命令行创建项目
bash
复制
npm create vite@latest按提示操作:
项目名称:输入你的项目名(如 vue3-demo)
选择框架:Vue
选择变体:TypeScript 或 JavaScript(按需选择)
进入项目目录并安装依赖:
bash
复制
cd vue3-demo npm install三、项目结构说明
复制
├── node_modules/ ├── public/ # 静态资源 ├── src/ │ ├── assets/ # 图片、字体等资源 │ ├── components/ # Vue 组件 │ ├── App.vue # 根组件 │ └── main.js # 入口文件 ├── index.html # 主页面 ├── vite.config.js # Vite 配置 ├── package.json四、启动开发服务器
bash
复制
npm run dev访问 http://localhost:5173 查看效果
五、开发 Vue 组件
创建组件 src/components/HelloWorld.vue
vue
复制
<template> <div> <h1>{{ msg }}</h1> <button @click="count++">Count: {{ count }}</button> </div> </template> <script setup> import { ref } from 'vue'; const props = defineProps({ msg: String }); const count = ref(0); </script>在 App.vue 中使用组件
vue
复制
<template> <HelloWorld msg="Welcome to Vue 3 + Vite!" /> </template> <script setup> import HelloWorld from './components/HelloWorld.vue'; </script>六、添加 Vue Router
安装路由:
bash
复制
npm install vue-router@4创建路由配置文件 src/router/index.js:
js
复制
import { createRouter, createWebHistory } from 'vue-router'; import Home from '../views/Home.vue'; const routes = [ { path: '/', component: Home }, { path: '/about', component: () => import('../views/About.vue') } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router;在 main.js 中挂载路由:
js
复制
import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; const app = createApp(App); app.use(router); app.mount('#app');七、状态管理 (Pinia)
安装 Pinia:
bash
复制
npm install pinia创建 Store src/stores/counter.js:
js
复制
import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++; } } });在组件中使用:
vue
复制
<script setup> import { useCounterStore } from '@/stores/counter'; const counter = useCounterStore(); </script> <template> <button @click="counter.increment">{{ counter.count }}</button> </template>八、构建与部署
生产环境构建:
bash
复制
npm run build生成的文件位于 dist/ 目录
本地预览生产版本:
bash
复制
npm run preview部署到服务器:
将 dist 目录上传至静态服务器(如 Nginx、Netlify、Vercel 等)
九、配置 Vite (可选)
修改 vite.config.js:
js
复制
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [vue()], base: '/your-subpath/', // 部署到子路径时配置 server: { port: 3000, // 自定义端口 } });十、常用插件推荐
UI 框架:
Element Plus:npm install element-plus
Vant:npm install vant
HTTP 请求:
Axios:npm install axios
代码规范:
ESLint + Prettier
Vue3和Vite从零开始搭建项目的详细步骤由讯客互联创业栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Vue3和Vite从零开始搭建项目的详细步骤”