前言
Vue 3 的 Composition API 是一个革命性的变化。它让我们能够更好地组织代码逻辑,提高代码的复用性。
ref 与 reactive
ref
ref 用于创建响应式的基础类型数据:
import { ref } from 'vue'
const count = ref(0)
count.value++ // 需要通过 .value 访问
reactive
reactive 用于创建响应式的对象:
import { reactive } from 'vue'
const state = reactive({
name: 'Jay',
age: 25,
})
state.name = 'New Name' // 直接修改
computed 计算属性
computed 用于派生状态,具有缓存特性:
import { ref, computed } from 'vue'
const firstName = ref('Jay')
const lastName = ref('Chen')
const fullName = computed(() => `${firstName.value} ${lastName.value}`)
watch 与 watchEffect
watch
精确监听指定的响应式数据:
import { ref, watch } from 'vue'
const query = ref('')
watch(query, (newVal, oldVal) => {
console.log(`搜索词从 "${oldVal}" 变为 "${newVal}"`)
})
watchEffect
自动追踪依赖:
import { ref, watchEffect } from 'vue'
const url = ref('/api/data')
watchEffect(async () => {
const response = await fetch(url.value)
const data = await response.json()
console.log(data)
})
自定义 Composable
将可复用的逻辑封装为 composable:
// composables/useCounter.ts
import { ref } from 'vue'
export function useCounter(initial = 0) {
const count = ref(initial)
function increment() { count.value++ }
function decrement() { count.value-- }
function reset() { count.value = initial }
return { count, increment, decrement, reset }
}
在组件中使用:
<script setup lang="ts">
import { useCounter } from '@/composables/useCounter'
const { count, increment, decrement } = useCounter(10)
</script>
<template>
<div>
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
</template>
最佳实践
- 优先使用
ref:在大多数场景下,ref比reactive更灵活 - 保持 composable 职责单一:每个 composable 只处理一个关注点
- 使用 TypeScript:类型安全让代码更可靠
- 避免在模板中放复杂逻辑:使用 computed 提取模板中的复杂表达式
总结
Composition API 让 Vue 3 的代码组织更加灵活和强大。合理使用 ref、computed、watch 和 composables,可以写出可维护性更好的代码。
评论💌 留下你的痕迹