Vue3 项目核心案例与实现要点

以下通过一个电商项目(如“小兔鲜”)的核心模块,展示 Vue3 项目开发中的关键技术实现。

1. 项目结构与核心配置

使用 Vue CLI 或 Vite 创建项目后,典型结构如下:

src/
├── assets/           # 静态资源
├── components/       # 可复用组件
├── views/           # 页面级组件
├── router/          # 路由配置
├── store/           # 状态管理 (Pinia)
├── utils/           # 工具函数
├── styles/          # 全局样式└── App.vue          # 根组件

路由配置示例 (Vue Router4)

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('../views/ProductDetail.vue'), // 路由懒加载 children: [ // 嵌套路由配置 {
        path: 'overview',
        component: () => import('../components/ProductOverview.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

路由懒加载可提升应用初始加载速度 。

2. 状态管理 (Pinia)

Pinia 是 Vue3 推荐的状态管理库,比 Vuex 更简洁。

定义 Store

// store/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    user: null }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    },
    async fetchUser(userId) { // 异步 action
      const response = await fetch(`/api/user/${userId}`)
      this.user = await response.json()
    }
  }
})

在组件中使用

<!-- Component.vue -->
<template>
  <div>
    <p>Count: {{ counterStore.count }}</p>
    <p>Double: {{ counterStore.doubleCount }}</p>
    <button @click="counterStore.increment()">Increment</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/store/counter'

const counterStore = useCounterStore()
// 可直接修改 state (Pinia 支持)
counterStore.count = 5
</script>

Pinia 提供了更直观的 Composition API 风格状态管理 。

3. 组件开发与逻辑复用

使用 <script setup> 语法糖,让 Composition API 更简洁。

组件示例:商品卡片

<!-- components/ProductCard.vue -->
<template>
  <div class="product-card">
    <!-- 图片懒加载 -->
    <img v-lazy="product.image" :alt="product.name" />
    <h3>{{ product.name }}</h3>
    <p>价格: {{ formatPrice(product.price) }}</p>
    <button @click="addToCart(product)">加入购物车</button>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useCartStore } from '@/store/cart'

const props = defineProps({
  product: {
    type: Object,
    required: true }
})

const cartStore = useCartStore()

// 计算属性
const formattedPrice = computed(() => `¥${props.product.price.toFixed(2)}`)

// 方法
const addToCart = (product) => {
  cartStore.addItem(product)
  // 可触发全局通知等副作用
}
</script>

使用 v-lazy 指令实现图片懒加载,优化性能 。

4.响应式大屏适配对于需要适配不同屏幕尺寸的管理后台,可使用 vue3-scale-box 组件。

安装与使用

npm install vue3-scale-box
<!-- App.vue 或布局组件 -->
<template>
  <ScaleBox :width="1920" :height="1080">
    <!-- 你的页面内容 -->
    <router-view />
  </ScaleBox>
</template>

<script setup>
import ScaleBox from 'vue3-scale-box'
</script>

该组件基于 CSS3 transform 实现等比例缩放,确保设计稿在不同分辨率下显示一致 。

5. 样式与主题定制

使用 CSS 变量和预处理器实现主题切换。

全局样式变量

/* styles/variables.css */
:root {
  --primary-color: #409eff;
  --bg-color: #f5f7fa;
  --text-color: #303133;
}

/* 暗黑主题 */
.dark-theme {
  --primary-color: #66b1ff;
  --bg-color: #1f1f1f;
  --text-color: #e5e7eb;
}

在组件中使用

<template>
  <button class="primary-btn">主题按钮</button>
</template>

<style scoped>
.primary-btn {
  background-color: var(--primary-color);
  color: white;
}
</style>

6.实用工具与最佳实践

场景 推荐方案 说明
HTTP 请求 Axios + 拦截器 统一处理请求/响应、错误
表单处理 VeeValidate + yup 强大的表单验证方案
图标库 Iconify + @iconify/vue 海量图标,按需引入
代码规范 ESLint + Prettier 统一代码风格
部署优化 组件懒加载 + 路由懒加载 减少首包体积

示例:Axios 封装

// utils/request.js
import axios from 'axios'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(
  response => response.data,
  error => {
    // 统一错误处理
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

export default service

项目启动与构建

// package.json 部分脚本
{
  "scripts": {
    "dev": "vite", // 开发环境 "build": "vue-tsc && vite build", // 生产构建 "preview": "vite preview" // 预览生产构建 }
}

通过以上案例可以看出,Vue3 项目开发应重点关注:组合式 API 的逻辑复用Pinia 状态管理基于 Vite 的构建优化组件化与代码组织。实际项目中可根据需求集成 UI 库(如 Element Plus)、图表库等生态工具。


参考来源

 

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐