Vue3 组合式API(二)
一、组合式API核心概念
1.1 setup函数:逻辑组织新范式
setup
是组合式API的入口函数,在组件创建前执行,替代了Vue2的data
、methods
等选项式API。通过<script setup>
语法糖可显著简化代码结构:
<script setup>
import { ref } from 'vue'
const count = ref(0)
const increment = () => count.value++
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>
此语法自动将顶层变量/函数暴露给模板,无需显式返回
1.2 响应式系统
- ref:处理基本类型和对象引用
const num = ref(0) // 通过.value访问 const obj = ref({ name: 'Vue' })
- reactive:深度响应式对象
const state = reactive({ user: { name: 'John' }, items: [] })
- shallowRef/reactive:浅层响应式(性能优化时使用)
1.3 生命周期钩子
选项式API | 组合式API |
---|---|
beforeCreate | 无对应(直接使用setup) |
created | 无对应 |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
示例:
import { onMounted } from 'vue'
onMounted(() => {
console.log('组件已挂载')
})
二、高级功能实践
2.1 逻辑复用模式
自定义Hook示例(useCounter):
// useCounter.js
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const increment = () => count.value++
const decrement = () => count.value--
return { count, increment, decrement }
}
组件中使用:
<script setup>
import { useCounter } from './useCounter'
const { count, increment } = useCounter(10)
</script>
2.2 异步状态管理
结合watchEffect
实现智能请求:
const { data, error, loading } = useFetch('/api/user')
function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(false)
watchEffect(async () => {
loading.value = true
try {
const res = await fetch(url)
data.value = await res.json()
} catch (e) {
error.value = e
} finally {
loading.value = false
}
})
return { data, error, loading }
}
2.3 依赖注入体系
父组件:
import { provide } from 'vue'
provide('theme', 'dark')
子组件:
import { inject } from 'vue'
const theme = inject('theme', 'light') // 默认值
三、企业级最佳实践
3.1 代码组织规范
逻辑分层:按功能模块划分代码块
// 用户相关逻辑 const { user, fetchUser } = useUser() // 订单相关逻辑 const { orders, loadOrders } = useOrder()
命名约定:
- Hook函数使用
use
前缀(如usePagination
) - 事件处理函数使用
handle
前缀(如handleSubmit
)
- Hook函数使用
TypeScript集成:
interface User { id: number name: string } const user = ref<User>({ id: 0, name: '' })
3.2 性能优化技巧
- 使用
computed
缓存计算值const fullName = computed(() => `${firstName} ${lastName}`)
- 精确控制侦听范围
watch([userId, page], ([newId, newPage]) => { fetchData(newId, newPage) }, { immediate: true })
- 大型列表使用
shallowRef
优化响应式开销
四、实战:用户管理系统
<script setup>
import { reactive, computed } from 'vue'
const state = reactive({
users: [],
searchQuery: '',
sortKey: 'name'
})
const filteredUsers = computed(() => {
return state.users.filter(u =>
u.name.includes(state.searchQuery)
).sort((a,b) => a[state.sortKey] > b[state.sortKey])
})
function addUser(user) {
state.users.push({ ...user, id: Date.now() })
}
</script>
<template>
<input v-model="state.searchQuery">
<select v-model="state.sortKey">
<option value="name">按姓名</option>
<option value="age">按年龄</option>
</select>
<UserTable :users="filteredUsers" @add="addUser" />
</template>
五、生态工具推荐
- VueUse:70+开箱即用的组合式API
- Pinia:新一代状态管理方案
- Volar:VSCode官方插件
- Vitest:组合式API友好测试框架
通过组合式API,开发者可以像搭积木一样构建组件逻辑。
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 万家灯火