Vue3 Composition API实战详解 从零基础到精通掌握函数式编程核心技巧 解决代码复用与逻辑组织痛点

引言:Vue 3 Composition API 的革命性意义
Vue 3 的 Composition API 是前端框架领域的一次重大革新,它彻底改变了我们组织和复用组件逻辑的方式。在 Vue 2 的 Options API 时代,开发者经常面临”逻辑碎片化”的问题:一个复杂的组件可能包含多个数据属性、方法、计算属性和生命周期钩子,这些逻辑按照选项类型分散在不同位置,导致代码难以维护和复用。
Composition API 通过引入
setup()
函数和一系列响应式 API,让我们能够基于逻辑功能而非选项类型来组织代码。这种函数式编程范式不仅解决了代码复用难题,还带来了更好的类型推导和更灵活的代码组织方式。
为什么需要 Composition API?
想象一个包含用户认证、表单验证和数据获取的复杂组件。在 Options API 中,这些逻辑会分散在
data
、
methods
、
computed
、
watch
和
mounted
等不同选项中。而 Composition API 允许我们将这些逻辑封装成独立的函数(Hooks),在需要的地方组合使用,就像搭积木一样灵活。
基础概念:Composition API 核心 API 详解
1.
ref
和
reactive
:响应式数据的创建
ref
和
reactive
是 Composition API 中创建响应式数据的两个核心函数。
import { ref, reactive } from ‘vue’

// ref 用于创建基本类型的响应式数据
const count = ref(0)
console.log(count.value) // 访问时需要 .value

// reactive 用于创建对象的响应式数据
const state = reactive({
name: ‘Alice’,
age: 25
})

// 在模板中使用时,ref 会自动解包,无需 .value
//

{{ count }}

// 在 script 中使用 ref 时必须 .value
count.value++
最佳实践
:
对于基本类型(string, number, boolean)使用
ref
对于对象和数组使用
reactive
在模板中,ref 会自动解包,但在 JavaScript 代码中必须使用
.value
2.
computed
:派生状态
计算属性用于创建依赖其他响应式数据的派生状态。
import { ref, computed } from ‘vue’

const firstName = ref(‘John’)
const lastName = ref(‘Doe’)

// 只读计算属性
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`
})

// 可写的计算属性
const price = ref(100)
const taxRate = ref(0.1)
const total = computed({
get: () => price.value * (1 + taxRate.value),
set: (newValue) => {
price.value = newValue / (1 + taxRate.value)
}
})

// 使用
console.log(fullName.value) // “John Doe”
total.value = 110 // 会触发 set 方法,price 变为 100
3.
watch
和
watchEffect
:响应式监听
import { ref, watch, watchEffect } from ‘vue’

const count = ref(0)
const name = ref(‘Alice’)

// watch:明确监听特定数据源
watch(count, (newValue, oldValue) => {
console.log(`count 从 ${oldValue} 变为 ${newValue}`)
})

// 监听多个源
watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
console.log(`数据变化: count=${newCount}, name=${newName}`)
})

// watchEffect:自动追踪依赖
watchEffect(() => {
// 只要在这个函数中访问了响应式数据,就会被追踪
console.log(`当前 count: ${count.value}, name: ${name.value}`)
})

// 立即执行一次,然后在依赖变化时重新执行
4.
computed
vs
watchEffect
的区别
特性
computed
watchEffect
返回值
返回一个响应式引用
不返回值(副作用)
惰性执行
惰性,只有在访问时才计算
立即执行并追踪依赖
缓存
有缓存,依赖不变不会重新计算
无缓存,每次依赖变化都执行
用途
派生状态
执行副作用
进阶技巧:自定义 Hooks 实现逻辑复用
1. 什么是自定义 Hooks?
自定义 Hooks 是 Composition API 的精髓,它允许我们将组件逻辑封装成可复用的函数。这类似于 React Hooks,但更灵活。
2. 实战案例:创建一个 useCounter Hook
// hooks/useCounter.js
import { ref, computed } from ‘vue’

export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const doubled = computed(() => count.value * 2)
const half = computed(() => count.value / 2)

function increment() {
count.value++
}

function decrement() {
count.value–
}

function reset() {
count.value = initialValue
}

return {
count,
doubled,
half,
increment,
decrement,
reset
}
}

// 在组件中使用
import { useCounter } from ‘@/hooks/useCounter’

export default {
setup() {
const { count, doubled, increment, decrement } = useCounter(10)

return {
count,
doubled,
increment,
decrement
}
}
}
3. 实战案例:创建一个 useFetch Hook
// hooks/useFetch.js
import { ref, watchEffect } from ‘vue’

export function useFetch(url) {
const data = ref(null)
const loading = ref(false)
const error = ref(null)

const fetchData = async () => {
loading.value = true
error.value = null
try {
const response = await fetch(url.value)
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
data.value = await response.json()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
}

// 当 URL 变化时自动重新获取
watchEffect(() => {
if (url.value) {
fetchData()
}
})

return {
data,
loading,
error,
refetch: fetchData
}
}

// 在组件中使用
import { ref } from ‘vue’
import { useFetch } from ‘@/hooks/useFetch’

export default {
setup() {
const userId = ref(1)
const { data, loading, error, refetch } = useFetch(
computed(() => `https://api.example.com/users/${userId.value}`)
)

return {
userId,
data,
loading,
error,
refetch
}
}
}
4. 实战案例:创建一个 useLocalStorage Hook
// hooks/useLocalStorage.js
import { ref, watch } from ‘vue’

export function useLocalStorage(key, defaultValue) {
// 从 localStorage 读取初始值
const storedValue = localStorage.getItem(key)
const data = ref(storedValue ? JSON.parse(storedValue) : defaultValue)

// 监听数据变化,同步到 localStorage
watch(data, (newValue) => {
localStorage.setItem(key, JSON.stringify(newValue))
}, { deep: true })

return data
}

// 在组件中使用
import { useLocalStorage } from ‘@/hooks/useLocalStorage’

export default {
setup() {
const theme = useLocalStorage(‘theme’, ‘light’)
const userSettings = useLocalStorage(‘userSettings’, {
notifications: true,
language: ‘zh-CN’
})

return {
theme,
userSettings
}
}
}
5. 实战案例:创建一个 useEventListener Hook
// hooks/useEventListener.js
import { onMounted, onUnmounted } from ‘vue’

export function useEventListener(event, handler, target = window) {
// 如果 target 是 ref,需要解包
const targetRef = ref(target)

onMounted(() => {
const element = targetRef.value || window
element.addEventListener(event, handler)
})

onUnmounted(() => {
const element = targetRef.value || window
element.removeEventListener(event, handler)
})
}

// 在组件中使用
import { useEventListener } from ‘@/hooks/useEventListener’

export default {
setup() {
const mouseX = ref(0)
const mouseY = ref(0)

useEventListener(‘mousemove’, (event) => {
mouseX.value = event.clientX
mouseY.value = event.clientY
})

return {
mouseX,
mouseY
}
}
}
解决痛点:代码复用与逻辑组织的最佳实践
1. Options API 的痛点分析
在 Options API 中,假设有以下场景:
一个组件需要处理用户认证
需要管理表单状态
需要获取远程数据
需要处理错误状态
这些逻辑会分散在:
// Options API – 逻辑分散
export default {
data() {
return {
user: null,
form: { email: ”, password: ” },
data: null,
loading: false,
error: null
}
},
methods: {
login() { /* … */ },
validateForm() { /* … */ },
fetchData() { /* … */ }
},
computed: {
isLoggedIn() { return !!this.user },
formValid() { /* … */ }
},
mounted() {
this.fetchData()
}
}
2. Composition API 的解决方案
使用 Composition API,我们可以按功能组织代码:
// hooks/useAuth.js
export function useAuth() {
const user = ref(null)
const isLoggedIn = computed(() => !!user.value)

async function login(email, password) {
try {
const response = await api.login(email, password)
user.value = response.user
return { success: true }
} catch (error) {
return { success: false, error: error.message }
}
}

function logout() {
user.value = null
}

return { user, isLoggedIn, login, logout }
}

// hooks/useForm.js
export function useForm(initialState) {
const form = reactive({ …initialState })
const errors = ref({})
const isValid = computed(() => Object.keys(errors.value).length === 0)

function validate(rules) {
errors.value = {}
Object.keys(rules).forEach(field => {
const rulesForField = rules[field]
const value = form[field]

rulesForField.forEach(rule => {
if (rule.required && !value) {
errors.value[field] = rule.message || ‘This field is required’
}
if (rule.pattern && !rule.pattern.test(value)) {
errors.value[field] = rule.message || ‘Invalid format’
}
})
})
}

return { form, errors, isValid, validate }
}

// 组件中使用
import { useAuth } from ‘@/hooks/useAuth’
import { useForm } from ‘@/hooks/useForm’
import { useFetch } from ‘@/hooks/useFetch’

export default {
setup() {
// 组合多个 Hooks
const { user, isLoggedIn, login } = useAuth()
const { form, errors, isValid, validate } = useForm({
email: ”,
password: ”
})
const { data, loading, error } = useFetch(
computed(() => isLoggedIn.value ? ‘/api/profile’ : null)
)

async function handleSubmit() {
validate({
email: [{ required: true, message: ‘邮箱必填’ }],
password: [{ required: true, message: ‘密码必填’ }]
})

if (!isValid.value) return

const result = await login(form.email, form.password)
if (!result.success) {
// 处理登录失败
}
}

return {
user,
isLoggedIn,
form,
errors,
isValid,
loading,
data,
handleSubmit
}
}
}
3. 逻辑组织的黄金法则
单一职责原则
:每个 Hook 只负责一个功能
// ❌ 不好的做法:一个 Hook 做太多事
function useComplexComponent() {
// 处理用户认证、表单、数据获取、错误处理…
}

// ✅ 好的做法:拆分成多个专注的 Hooks
function useAuth() { /* … */ }
function useForm() { /* … */ }
function useFetch() { /* … */ }
function useErrorHandling() { /* … */ }
组合优于继承
:通过组合多个简单 Hook 创建复杂功能
// 创建一个完整的页面逻辑
function useUserPage(userId) {
const { user, loading: userLoading } = useUser(userId)
const { posts, loading: postsLoading } = useUserPosts(userId)
const { follow, unfollow, isFollowing } = useFollow(userId)

const isLoading = computed(() => userLoading.value || postsLoading.value)

return {
user,
posts,
isLoading,
follow,
unfollow,
isFollowing
}
}
精通技巧:高级模式与性能优化
1. 响应式解构:toRefs 和 toRef
当从 reactive 对象中解构属性时,会失去响应性。使用
toRefs
解决:
import { reactive, toRefs, toRef } from ‘vue’

function useUser() {
const state = reactive({
name: ‘Alice’,
age: 25,
email: ‘alice@example.com’
})

// ❌ 失去响应性
const { name, age } = state

// ✅ 保持响应性
const { name, age } = toRefs(state)

// ✅ 或者只转换特定属性
const name = toRef(state, ‘name’)

return {
…toRefs(state) // 解构后仍保持响应性
}
}

// 在组件中使用
const { name, age } = useUser()
// name.value 和 age.value 仍然保持响应性
2. 依赖注入:provide 和 inject
在深层嵌套组件中共享状态:
// 祖先组件
import { provide, ref } from ‘vue’

export default {
setup() {
const theme = ref(‘light’)

// 提供数据
provide(‘theme’, theme)

// 提供方法
function toggleTheme() {
theme.value = theme.value === ‘light’ ? ‘dark’ : ‘light’
}

provide(‘toggleTheme’, toggleTheme)
}
}

// 后代组件
import { inject } from ‘vue’

export default {
setup() {
// 注入数据
const theme = inject(‘theme’, ‘light’) // 第二个参数是默认值

// 注入方法
const toggleTheme = inject(‘toggleTheme’)

return { theme, toggleTheme }
}
}
3. 自定义指令与 Hooks 结合
// hooks/useInfiniteScroll.js
export function useInfiniteScroll(callback, options = {}) {
const isLoading = ref(false)

const handleScroll = async () => {
if (isLoading.value) return

const { scrollTop, scrollHeight, clientHeight } = document.documentElement

if (scrollTop + clientHeight >= scrollHeight – 100) {
isLoading.value = true
await callback()
isLoading.value = false
}
}

useEventListener(‘scroll’, handleScroll)

return { isLoading }
}

// 在组件中使用
export default {
setup() {
const posts = ref([])
const page = ref(1)

const loadMore = async () => {
const newPosts = await fetchPosts(page.value)
posts.value.push(…newPosts)
page.value++
}

const { isLoading } = useInfiniteScroll(loadMore)

return { posts, isLoading }
}
}
4. 性能优化:避免不必要的响应式
import { ref, shallowRef, shallowReactive } from ‘vue’

// 对于大型列表数据,使用 shallowRef 避免深度监听
const bigList = shallowRef([])

// 对于对象,如果只需要监听顶层属性变化
const state = shallowReactive({
user: { name: ‘Alice’ }, // user 的变化不会触发更新
count: 0 // count 的变化会触发更新
})

// 使用 markRaw 标记不需要响应式的对象
import { markRaw } from ‘vue’

function useLargeData() {
const data = ref(markRaw({
// 这个对象不会被转换为响应式
hugeArray: Array.from({ length: 10000 }, (_, i) => ({ id: i }))
}))

return { data }
}
5. 与 TypeScript 完美结合
// hooks/useCounter.ts
import { ref, computed } from ‘vue’

interface CounterOptions {
min?: number
max?: number
step?: number
}

interface CounterResult {
count: Ref
doubled: Readonly>
increment: () => void
decrement: () => void
reset: () => void
}

export function useCounter(
initialValue: number = 0,
options: CounterOptions = {}
): CounterResult {
const { min = -Infinity, max = Infinity, step = 1 } = options

const count = ref(initialValue)

const doubled = computed(() => count.value * 2)

const increment = (): void => {
if (count.value + step <= max) { count.value += step } } const decrement = (): void => {
if (count.value – step >= min) {
count.value -= step
}
}

const reset = (): void => {
count.value = initialValue
}

return {
count,
doubled,
increment,
decrement,
reset
}
}

// 使用
const { count, increment } = useCounter(0, { min: 0, max: 10 })
实战项目:构建一个完整的 Composition API 应用
1. 项目结构
src/
├── hooks/
│ ├── useAuth.js
│ ├── useForm.js
│ ├── useFetch.js
│ ├── useLocalStorage.js
│ └── useNotification.js
├── components/
│ ├── UserForm.vue
│ └── PostList.vue
├── App.vue
└── main.js
2. 完整示例:用户管理后台
// hooks/useUserManager.js
import { ref, reactive, computed } from ‘vue’
import { useFetch } from ‘./useFetch’
import { useLocalStorage } from ‘./useLocalStorage’

export function useUserManager() {
// 本地存储用户偏好
const pageSize = useLocalStorage(‘pageSize’, 10)
const sortBy = useLocalStorage(‘sortBy’, ‘name’)

// 搜索和过滤状态
const searchQuery = ref(”)
const filterRole = ref(‘all’)

// 获取用户列表
const {
data: users,
loading,
error,
refetch
} = useFetch(
computed(() => {
const params = new URLSearchParams({
page: ‘1’,
limit: pageSize.value,
search: searchQuery.value,
role: filterRole.value,
sort: sortBy.value
})
return `/api/users?${params}`
})
)

// 选中的用户
const selectedUsers = ref([])

// 批量操作状态
const batchAction = reactive({
active: false,
type: null,
processing: false
})

// 计算属性
const filteredUsers = computed(() => {
if (!users.value) return []

return users.value.filter(user => {
const matchesSearch = user.name.toLowerCase().includes(
searchQuery.value.toLowerCase()
)
const matchesFilter = filterRole.value === ‘all’ ||
user.role === filterRole.value
return matchesSearch && matchesFilter
})
})

const hasSelection = computed(() => selectedUsers.value.length > 0)

// 方法
function toggleSelection(userId) {
const index = selectedUsers.value.indexOf(userId)
if (index > -1) {
selectedUsers.value.splice(index, 1)
} else {
selectedUsers.value.push(userId)
}
}

function selectAll() {
if (!users.value) return
selectedUsers.value = users.value.map(u => u.id)
}

function clearSelection() {
selectedUsers.value = []
}

async function deleteUser(userId) {
if (!confirm(‘确定删除该用户吗?’)) return

try {
await fetch(`/api/users/${userId}`, { method: ‘DELETE’ })
// 重新获取列表
await refetch()
// 显示通知
showNotification(‘用户已删除’, ‘success’)
} catch (e) {
showNotification(‘删除失败: ‘ + e.message, ‘error’)
}
}

async function batchDelete() {
if (!hasSelection.value) return

batchAction.active = true
batchAction.type = ‘delete’
batchAction.processing = true

try {
await Promise.all(
selectedUsers.value.map(id =>
fetch(`/api/users/${id}`, { method: ‘DELETE’ })
)
)
clearSelection()
await refetch()
showNotification(`批量删除 ${selectedUsers.value.length} 个用户成功`, ‘success’)
} catch (e) {
showNotification(‘批量删除失败: ‘ + e.message, ‘error’)
} finally {
batchAction.processing = false
batchAction.active = false
}
}

// 通知系统(来自另一个 Hook)
const { showNotification } = useNotification()

return {
// 状态
users: filteredUsers,
loading,
error,
searchQuery,
filterRole,
pageSize,
sortBy,
selectedUsers,
batchAction,

// 计算属性
hasSelection,

// 方法
toggleSelection,
selectAll,
clearSelection,
deleteUser,
batchDelete,
refetch
}
}

// 组件中使用
import { useUserManager } from ‘@/hooks/useUserManager’

export default {
setup() {
const {
users,
loading,
error,
searchQuery,
filterRole,
pageSize,
sortBy,
selectedUsers,
hasSelection,
toggleSelection,
selectAll,
clearSelection,
deleteUser,
batchDelete
} = useUserManager()

return {
users,
loading,
error,
searchQuery,
filterRole,
pageSize,
sortBy,
selectedUsers,
hasSelection,
toggleSelection,
selectAll,
clearSelection,
deleteUser,
batchDelete
}
}
}
总结与最佳实践
1. Composition API 的核心优势
逻辑复用
:通过自定义 Hooks 实现逻辑的跨组件复用
代码组织
:基于功能而非选项类型组织代码,更符合直觉
类型安全
:与 TypeScript 完美集成
灵活性
:可以自由组合多个 Hooks,创建复杂功能
可维护性
:每个 Hook 职责单一,易于测试和维护
2. 何时使用 Composition API vs Options API
推荐使用 Composition API 的场景
:
需要复用逻辑的组件
复杂的组件(超过 200 行)
需要 TypeScript 支持的项目
团队协作,需要清晰的代码结构
Options API 仍然适用
:
简单的组件
快速原型开发
团队对 Options API 更熟悉
3. 最终建议
从小处开始
:先在新功能中使用 Composition API
逐步迁移
:对现有复杂组件进行渐进式重构
建立规范
:团队内部统一 Hook 命名和结构规范
文档化
:为自定义 Hooks 编写清晰的文档和使用示例
测试驱动
:为 Hooks 编写单元测试,确保可靠性
通过掌握 Composition API,你不仅能解决代码复用和逻辑组织的痛点,还能拥抱函数式编程的优雅范式,构建更可维护、更灵活的 Vue 应用。