2026-08-07 13:17:54
|
0 阅读
|
分类:技术博客
从 Options API 到 Composition API
作为一名在合肥工作了5年的前端工程师我见证了 Vue 从2.x 到3.x 的演进过程。说实话刚开始接触 Vue3 的 Composition API 时我是抗拒的——"Options API 用得好好的为什么要改?"但当我真正深入使用了一段时间后发现 Composition API 解决了 Options API 在大型项目中遇到的很多痛点。
逻辑复用:在 Options API 中如果我们想在多个组件之间共享逻辑(如表单验证/权限控制/分页等)通常使用 Mixin 但 Mixin 存在命名冲突/来源不清晰等问题。Composition API 通过自定义 Hook(composable function)完美解决了这个问题——把相关的逻辑封装到一个函数中在任何组件中调用即可。更好的 TypeScript 支持:Options API 中 this 的类型推断一直是个老大难问题。Composition API 推崇函数式编程天然更适合 TypeScript 的类型推导代码补全和错误检查都更准确。更灵活的代码组织:Options API 强制按照 data/methods/computed/watch 等选项组织代码当一个组件的功能复杂时同一个功能的代码会被分散到不同选项中上下跳转很累。Composition API 允许我们把相关功能组织在一起代码可读性大大提升。
TypeScript 与 Vue3 的完美结合
Vue3 从底层就是用 TypeScript 重写的所以 TS 和 Vue3 是天生一对。以下是一些实用的类型定义技巧:
Props 类型定义:
<script setup lang="ts">
interface Props {
title: string
count?: number // 可选
items: Article[] // 自定义类型
callback: (id: number) => void // 函数类型
}
const props = withDefaults(defineProps<Props>(), {
count: 0,
items: () => []
})
</script>
Emits 类型定义:
const emit = defineEmits<{
update: [value: string]
delete: [id: number]
}>()
Ref 和 Reactive 的类型:
// Ref
const count = ref<number>(0)
const user = ref<User | null>(null)
// Reactive
const state = reactive<{
loading: boolean
error: string | null
data: Article[]
}>({
loading: false,
error: null,
data: []
})