分类 前端技术 下的文章

Vue3组合式API实战:大型项目管理经验

Vue3的组合式API(Composition API)为大型前端项目带来了革命性的改进。通过更灵活的逻辑组织和更好的TypeScript支持,组合式API让我们能够构建更可维护、可测试的前端应用。本文将分享在大型项目中应用组合式API的实践经验。

组合式API基础

1. Setup函数与响应式数据

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
    <p>Doubled: {{ doubledCount }}</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 响应式数据
const count = ref(0)

// 计算属性
const doubledCount = computed(() => count.value * 2)

// 方法
function increment() {
  count.value++
}
</script>

2. 组合式函数(Composables)

组合式函数是组合式API的核心,用于逻辑复用:

// useCounter.js
import { ref, computed } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  
  const doubled = computed(() => count.value * 2)
  const tripled = computed(() => count.value * 3)
  
  function increment() {
    count.value++
  }
  
  function decrement() {
    count.value--
  }
  
  function reset() {
    count.value = initialValue
  }
  
  return {
    count,
    doubled,
    tripled,
    increment,
    decrement,
    reset
  }
}

使用组合式函数:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Doubled: {{ doubled }}</p>
    <p>Tripled: {{ tripled }}</p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="reset">Reset</button>
  </div>
</template>

<script setup>
import { useCounter } from './useCounter.js'

const { count, doubled, tripled, increment, decrement, reset } = useCounter(10)
</script>

大型项目实践

1. 状态管理策略

在大型项目中,合理组织状态至关重要:

// store/userStore.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref(null)
  const permissions = ref([])
  const loading = ref(false)
  const error = ref(null)
  
  // getters
  const isLoggedIn = computed(() => !!user.value)
  const hasPermission = (permission) => 
    computed(() => permissions.value.includes(permission))
  
  // actions
  async function login(credentials) {
    loading.value = true
    error.value = null
    
    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
      })
      
      if (!response.ok) {
        throw new Error('Login failed')
      }
      
      const data = await response.json()
      user.value = data.user
      permissions.value = data.permissions
      
      return data
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }
  
  function logout() {
    user.value = null
    permissions.value = []
  }
  
  return {
    user,
    permissions,
    loading,
    error,
    isLoggedIn,
    hasPermission,
    login,
    logout
  }
})

2. API请求封装

// composables/useApi.js
import { ref } from 'vue'

export function useApi(baseURL = '') {
  const loading = ref(false)
  const error = ref(null)
  const data = ref(null)
  
  async function fetchData(endpoint, options = {}) {
    loading.value = true
    error.value = null
    
    try {
      const url = `${baseURL}${endpoint}`
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        },
        ...options
      })
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      
      data.value = await response.json()
      return data.value
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function postData(endpoint, body, options = {}) {
    return fetchData(endpoint, {
      method: 'POST',
      body: JSON.stringify(body),
      ...options
    })
  }
  
  async function putData(endpoint, body, options = {}) {
    return fetchData(endpoint, {
      method: 'PUT',
      body: JSON.stringify(body),
      ...options
    })
  }
  
  async function deleteData(endpoint, options = {}) {
    return fetchData(endpoint, {
      method: 'DELETE',
      ...options
    })
  }
  
  return {
    loading,
    error,
    data,
    fetchData,
    postData,
    putData,
    deleteData
  }
}

3. 表单处理组合式函数

// composables/useForm.js
import { ref, computed } from 'vue'

export function useForm(initialValues = {}, validationRules = {}) {
  const formValues = ref({ ...initialValues })
  const errors = ref({})
  const touched = ref({})
  const isSubmitting = ref(false)
  
  // 验证表单
  const validate = () => {
    errors.value = {}
    
    Object.keys(validationRules).forEach(field => {
      const rules = validationRules[field]
      const value = formValues.value[field]
      
      rules.forEach(rule => {
        if (!rule.validator(value, formValues.value)) {
          if (!errors.value[field]) {
            errors.value[field] = []
          }
          errors.value[field].push(rule.message)
        }
      })
    })
    
    return Object.keys(errors.value).length === 0
  }
  
  // 字段验证
  const validateField = (field) => {
    if (!validationRules[field]) return true
    
    errors.value[field] = []
    const rules = validationRules[field]
    const value = formValues.value[field]
    
    rules.forEach(rule => {
      if (!rule.validator(value, formValues.value)) {
        errors.value[field].push(rule.message)
      }
    })
    
    return errors.value[field].length === 0
  }
  
  // 重置表单
  const reset = () => {
    formValues.value = { ...initialValues }
    errors.value = {}
    touched.value = {}
  }
  
  // 表单状态
  const isValid = computed(() => validate())
  const isDirty = computed(() => {
    return Object.keys(formValues.value).some(key => 
      formValues.value[key] !== initialValues[key]
    )
  })
  
  // 字段处理
  const handleChange = (field, value) => {
    formValues.value[field] = value
    touched.value[field] = true
    validateField(field)
  }
  
  const handleBlur = (field) => {
    touched.value[field] = true
    validateField(field)
  }
  
  return {
    formValues,
    errors,
    touched,
    isSubmitting,
    isValid,
    isDirty,
    validate,
    validateField,
    reset,
    handleChange,
    handleBlur
  }
}

// 使用示例
const validationRules = {
  email: [
    {
      validator: (value) => value && value.includes('@'),
      message: '请输入有效的邮箱地址'
    },
    {
      validator: (value) => value && value.length > 0,
      message: '邮箱不能为空'
    }
  ],
  password: [
    {
      validator: (value) => value && value.length >= 8,
      message: '密码至少8个字符'
    }
  ]
}

性能优化技巧

1. 组件懒加载

// 路由配置中的懒加载
import { defineAsyncComponent } from 'vue'

const routes = [
  {
    path: '/dashboard',
    component: defineAsyncComponent(() =>
      import('./views/Dashboard.vue')
    )
  },
  {
    path: '/settings',
    component: defineAsyncComponent(() =>
      import('./views/Settings.vue')
    )
  }
]

// 条件懒加载组件
const AsyncModal = defineAsyncComponent({
  loader: () => import('./components/Modal.vue'),
  loadingComponent: LoadingSpinner,
  errorComponent: ErrorComponent,
  delay: 200,
  timeout: 3000
})

2. 列表虚拟滚动

<template>
  <div ref="containerRef" class="virtual-list-container" @scroll="handleScroll">
    <div :style="{ height: totalHeight + 'px' }">
      <div 
        v-for="item in visibleItems" 
        :key="item.id"
        :style="{ transform: `translateY(${item.offset}px)` }"
        class="virtual-list-item"
      >
        {{ item.content }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const props = defineProps({
  items: {
    type: Array,
    required: true
  },
  itemHeight: {
    type: Number,
    default: 50
  },
  buffer: {
    type: Number,
    default: 5
  }
})

const containerRef = ref(null)
const scrollTop = ref(0)
const containerHeight = ref(0)

// 总高度
const totalHeight = computed(() => props.items.length * props.itemHeight)

// 可见项范围
const startIndex = computed(() => {
  return Math.max(0, Math.floor(scrollTop.value / props.itemHeight) - props.buffer)
})

const endIndex = computed(() => {
  const visibleCount = Math.ceil(containerHeight.value / props.itemHeight)
  return Math.min(
    props.items.length,
    Math.ceil((scrollTop.value + containerHeight.value) / props.itemHeight) + props.buffer
  )
})

// 可见项
const visibleItems = computed(() => {
  return props.items.slice(startIndex.value, endIndex.value).map((item, index) => ({
    ...item,
    offset: (startIndex.value + index) * props.itemHeight
  }))
})

function handleScroll() {
  if (containerRef.value) {
    scrollTop.value = containerRef.value.scrollTop
  }
}

onMounted(() => {
  if (containerRef.value) {
    containerHeight.value = containerRef.value.clientHeight
  }
})
</script>

<style scoped>
.virtual-list-container {
  height: 500px;
  overflow-y: auto;
  position: relative;
}

.virtual-list-item {
  position: absolute;
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  padding: 0 16px;
}
</style>

3. 防抖与节流组合式函数

// composables/useDebounce.js
import { ref, watch } from 'vue'

export function useDebounce(value, delay = 500) {
  const debouncedValue = ref(value.value)
  let timeoutId
  
  watch(value, (newValue) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      debouncedValue.value = newValue
    }, delay)
  }, { immediate: true })
  
  const cancel = () => {
    clearTimeout(timeoutId)
  }
  
  return {
    debouncedValue,
    cancel
  }
}

// composables/useThrottle.js
import { ref, watch } from 'vue'

export function useThrottle(value, limit = 500) {
  const throttledValue = ref(value.value)
  let lastCall = 0
  let timeoutId
  
  watch(value, (newValue) => {
    const now = Date.now()
    const remaining = limit - (now - lastCall)
    
    if (remaining <= 0) {
      // 立即执行
      lastCall = now
      throttledValue.value = newValue
    } else if (!timeoutId) {
      // 延迟执行
      timeoutId = setTimeout(() => {
        lastCall = Date.now()
        throttledValue.value = newValue
        timeoutId = null
      }, remaining)
    }
  }, { immediate: true })
  
  const cancel = () => {
    if (timeoutId) {
      clearTimeout(timeoutId)
      timeoutId = null
    }
  }
  
  return {
    throttledValue,
    cancel
  }
}

// 使用示例
const searchQuery = ref('')
const { debouncedValue: debouncedQuery } = useDebounce(searchQuery, 300)

watch(debouncedQuery, (newQuery) => {
  // 只有在用户停止输入300ms后才会触发搜索
  if (newQuery) {
    performSearch(newQuery)
  }
})

测试策略

1. 组合式函数测试

// __tests__/useCounter.spec.js
import { renderHook, act } from '@testing-library/vue'
import { useCounter } from '../useCounter'

describe('useCounter', () => {
  it('should initialize with default value', () => {
    const { result } = renderHook(() => useCounter())
    expect(result.current.count.value).toBe(0)
  })
  
  it('should initialize with custom value', () => {
    const { result } = renderHook(() => useCounter(10))
    expect(result.current.count.value).toBe(10)
  })
  
  it('should increment counter', () => {
    const { result } = renderHook(() => useCounter(5))
    
    act(() => {
      result.current.increment()
    })
    
    expect(result.current.count.value).toBe(6)
    expect(result.current.doubled.value).toBe(12)
  })
  
  it('should decrement counter', () => {
    const { result } = renderHook(() => useCounter(5))
    
    act(() => {
      result.current.decrement()
    })
    
    expect(result.current.count.value).toBe(4)
  })
  
  it('should reset counter', () => {
    const { result } = renderHook(() => useCounter(5))
    
    act(() => {
      result.current.increment()
      result.current.increment()
      result.current.reset()
    })
    
    expect(result.current.count.value).toBe(5)
  })
})

2. 组件测试

// __tests__/UserProfile.spec.js
import { mount } from '@vue/test-utils'
import UserProfile from '../UserProfile.vue'
import { createPinia, setActivePinia } from 'pinia'

describe('UserProfile', () => {
  let pinia
  
  beforeEach(() => {
    pinia = createPinia()
    setActivePinia(pinia)
  })
  
  it('should render user information', async () => {
    const wrapper = mount(UserProfile, {
      global: {
        plugins: [pinia]
      },
      props: {
        userId: 1
      }
    })
    
    // 等待异步数据加载
    await wrapper.vm.()
    
    expect(wrapper.find('.user-name').text()).toBe('John Doe')
    expect(wrapper.find('.user-email').text()).toBe('john@example.com')
  })
  
  it('should show loading state', () => {
    const wrapper = mount(UserProfile, {
      global: {
        plugins: [pinia]
      },
      props: {
        userId: 1
      }
    })
    
    expect(wrapper.find('.loading-spinner').exists()).toBe(true)
  })
  
  it('should show error message', async () => {
    // Mock API失败
    jest.spyOn(global, 'fetch').mockRejectedValue(new Error('Network error'))
    
    const wrapper = mount(UserProfile, {
      global: {
        plugins: [pinia]
      },
      props: {
        userId: 1
      }
    })
    
    await wrapper.vm.()
    
    expect(wrapper.find('.error-message').text()).toContain('Network error')
  })
})

项目结构组织

推荐的项目结构

src/
├── components/           # 通用组件
│   ├── common/          # 全局通用组件
│   ├── layout/          # 布局组件
│   └── ui/              # UI基础组件
├── composables/         # 组合式函数
│   ├── useApi.js        # API请求
│   ├── useForm.js       # 表单处理
│   ├── useAuth.js       # 认证逻辑
│   └── index.js         # 统一导出
├── stores/              # Pinia状态管理
│   ├── userStore.js
│   ├── appStore.js
│   └── index.js
├── views/               # 页面组件
│   ├── Home.vue
│   ├── Dashboard.vue
│   └── Settings.vue
├── router/              # 路由配置
│   ├── index.js
│   └── guards.js
├── utils/               # 工具函数
│   ├── validators.js
│   ├── formatters.js
│   └── constants.js
├── assets/              # 静态资源
├── styles/              # 全局样式
├── types/               # TypeScript类型定义
└── main.js              # 应用入口

统一导出模式

// composables/index.js
export { useApi } from './useApi'
export { useForm } from './useForm'
export { useAuth } from './useAuth'
export { useDebounce } from './useDebounce'
export { useThrottle } from './useThrottle'

// 使用示例
import { useApi, useForm } from '@/composables'

最佳实践总结

  1. 逻辑复用优先:使用组合式函数提取可复用逻辑
  2. 状态管理清晰:合理划分store,避免全局状态滥用
  3. 性能意识:使用懒加载、虚拟滚动等技术优化性能
  4. 类型安全:充分利用TypeScript的类型系统
  5. 测试覆盖:为组合式函数和复杂组件编写测试
  6. 代码分割:按路由和功能模块进行代码分割
  7. 错误处理:统一的错误处理和用户反馈
  8. 响应式设计:考虑不同设备和屏幕尺寸

常见问题与解决方案

1. 组合式函数之间的依赖

// 正确的依赖管理
import { useAuth } from './useAuth'
import { useApi } from './useApi'

export function useUserProfile() {
  const { user } = useAuth()
  const { fetchData, loading, error } = useApi()
  
  const userProfile = ref(null)
  
  async function loadProfile() {
    if (!user.value) return
    
    try {
      userProfile.value = await fetchData(`/users/${user.value.id}/profile`)
    } catch (err) {
      console.error('Failed to load profile:', err)
    }
  }
  
  watch(user, (newUser) => {
    if (newUser) {
      loadProfile()
    } else {
      userProfile.value = null
    }
  }, { immediate: true })
  
  return {
    userProfile,
    loading,
    error,
    loadProfile
  }
}

2. 内存泄漏预防

import { onUnmounted } from 'vue'

export function useEventListener(target, event, handler) {
  // 添加事件监听
  target.addEventListener(event, handler)
  
  // 组件卸载时移除
  onUnmounted(() => {
    target.removeEventListener(event, handler)
  })
}

export function useInterval(callback, delay) {
  let intervalId
  
  const start = () => {
    intervalId = setInterval(callback, delay)
  }
  
  const stop = () => {
    if (intervalId) {
      clearInterval(intervalId)
      intervalId = null
    }
  }
  
  // 自动清理
  onUnmounted(stop)
  
  return {
    start,
    stop
  }
}

结语

Vue3的组合式API为大型前端项目开发带来了全新的可能性。通过合理的架构设计和最佳实践,我们可以构建出更可维护、可测试、高性能的前端应用。在实践中不断总结经验,持续优化代码结构,才能真正发挥组合式API的优势。

提示:在迁移现有Vue2项目到Vue3时,建议逐步采用组合式API,先从新功能开始,逐步重构旧代码。请输入代码