npm create vite@latest my-vue3-project -- --template vue# 或使用 yarn create vite my-vue3-project --template vue
npm install -g @vue/clivue create my-vue3-project
选择 Manually select features
勾选 Vue 3 和所需功能(TypeScript、Router、Pinia 等)
vite.config.js(Vue 3 默认使用 Vite)javascriptimport { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src') // 路径别名
}
},
server: {
port: 3000, // 开发服务器端口
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
build: {
outDir: 'dist', // 打包输出目录
assetsDir: 'assets' // 静态资源目录
}
});
npm install axios sass pinia @element-plus/icons-vue element-plus# 或使用 yarn add axios sass pinia @element-plus/icons-vue element-plus
在 src/main.js 中:
javascriptimport { createApp } from 'vue';
import App from './App.vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
const app = createApp(App);
app.use(ElementPlus);
app.mount('#app');
在 src/router/index.js 中:
javascriptimport { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue') // **异步加载组件**
}
];
const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), // **使用 `import.meta`** routes});
export default router;
在 src/store/index.js 中:
javascriptimport { defineStore } from 'pinia';
export const useMainStore = defineStore('main', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++; },
async incrementAsync() {
setTimeout(() => this.increment(), 1000); }
}
});
markdown├── src│ ├── assets │ ├── components │ ├── views │ ├── router # 使用 Vue Router 4+ │ ├── store # 使用 Pinia 替代 Vuex │ ├── App.vue # **使用 `<script setup>` 语法** │ └── main.js # **使用 `createApp` 初始化** ├── vite.config.js # 替代 vue.config.js └── package.json # 依赖包含 "vue": "^3.x.x"
在组件中使用 <script setup>:
vue<script setup>import { ref } from 'vue';
const count = ref(0);
</script>
创建 .env.development 和 .env.production 文件
变量必须以 VITE_ 开头(不再是 VUE_APP_)
bashVITE_API_URL=http://api.example.com
bashnpm run dev # Vite 开发模式(**不再是 `serve`**)npm run build # 生产构建npm run preview # 预览生产构建
浏览器兼容性:Vue 3 默认不支持 IE11,如需兼容需额外配置。
组合式 API:推荐使用 <script setup> 语法替代 Options API。
TypeScript 支持:Vite 默认集成 TS,可通过 --template vue-ts 创建 TS 项目。
Vue 2 迁移:官方提供迁移工具 @vue/compat,但建议新项目直接使用 Vue 3 特性。
通过以上步骤,即可快速搭建一个现代化的 Vue 3 项目并完成基础配置。