vue项目实现流程
Vue项目实现流程
项目初始化
使用Vue CLI或Vite创建项目,Vue CLI适合传统项目,Vite适合现代轻量级项目。安装Node.js后运行以下命令:
npm init vue@latest # Vue CLI
npm create vite@latest # Vite
选择需要的配置(如TypeScript、Router、Pinia等),完成初始化后安装依赖:
cd project-name
npm install
目录结构规划
典型Vue 3项目目录结构如下:
src/
├── assets/ # 静态资源
├── components/ # 公共组件
├── composables/ # 组合式函数
├── router/ # 路由配置
├── stores/ # 状态管理
├── views/ # 页面级组件
├── App.vue # 根组件
└── main.js # 入口文件
路由配置
安装Vue Router并配置路由表:
npm install vue-router
在router/index.js中定义路由:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{ path: '/', component: HomeView },
{ path: '/about', component: () => import('../views/AboutView.vue') }
]
const router = createRouter({
history: createWebHistory(),
routes
})
状态管理
使用Pinia进行状态管理:
npm install pinia
创建store文件(如stores/counter.js):
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
组件开发
单文件组件(SFC)基本结构:
<template>
<div>{{ message }}</div>
<button @click="increment">+1</button>
</template>
<script setup>
import { ref } from 'vue'
import { useCounterStore } from '@/stores/counter'
const message = ref('Hello Vue 3')
const counter = useCounterStore()
const increment = () => counter.increment()
</script>
<style scoped>
button { color: #42b983; }
</style>
API交互
使用axios进行HTTP请求:
npm install axios
封装API请求:
// src/api/auth.js
import axios from 'axios'
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
})
export const login = (credentials) => api.post('/login', credentials)
构建部署
开发模式运行:
npm run dev
生产环境构建:
npm run build
生成dist目录后可通过Nginx等服务器部署,或使用Vercel/Netlify等平台托管。







