组合式 API 与 TypeScript 配合
组合式 API 不是"另一种写法",是 Vue3 组织代码的主方式:把同一个逻辑的数据、计算、侦听、清理写在一起,而不是按选项类型打散到四个块里。TypeScript 支持是它诞生的主要动机之一。这篇覆盖 setup、生命周期、composable 规范,以及 TS 配合里最容易踩的类型坑。
一、为什么需要组合式 API
同一个"用户列表"功能,在选项式里长这样:data 里三个字段、computed 里两个派生、watch 里一个侦听、methods 里五个操作——读代码要在选项间跳六次。功能一多(加搜索、加分页、加批量选择),组件膨胀到几百行,某个字段删了不敢确认哪块还在用。
组合式的组织方式:
// 一个功能一个 useXxx,组件里就是清单式调用
const { users, loading, reload } = useUserList();
const { keyword, filtered } = useKeywordFilter(users);
const selection = useSelection(filtered);三个收益:逻辑内聚、复用单元是函数(不是 mixins 的隐式合并)、TS 类型自然推导。
二、setup 的两种用法
2.1 setup() 选项
import { ref, onMounted } from 'vue';
export default {
props: ['id'],
setup(props, { attrs, slots, emit }) {
const count = ref(0);
onMounted(() => console.log('mounted'));
return { count }; // 暴露给模板和其他选项
},
created() {
// this.count 可以访问 setup 返回的绑定
}
};- 执行时机:在
beforeCreate之前,所以 setup 里没有this(此时实例还没初始化)。要访问 props 用第一个参数,访问 attrs/slots/emit 用第二个参数 context。 - 返回值:返回对象绑定到模板;返回渲染函数则直接当 render 用。
- 和选项式混用:可以,
created等钩子里能拿到 setup 的返回值,但不推荐混搭,风格分裂后最难维护。
2.2 script setup(推荐)
<script setup>
import { ref, onMounted } from 'vue';
const props = defineProps({ id: Number }); // 声明 props
const emit = defineEmits(['change']); // 声明事件
const count = ref(0);
onMounted(() => { /* ... */ });
defineExpose({ focus }); // 暴露给父组件 ref
</script>- 顶层绑定自动暴露给模板,不需要 return。
- 宏(defineProps 等)编译时提升,只能写在顶层。
- 每个 SFC 只能有一个
<script setup>;需要额外普通 script 时(如declare全局类型、副作用代码)可以并存两个<script>块。 - 想用选项式能力:
defineOptions({ name: 'MyComp', inheritAttrs: false })。
三、组合式生命周期钩子
| 钩子 | 选项式对应 |
|---|---|
onBeforeMount | beforeMount |
onMounted | mounted |
onBeforeUpdate | beforeUpdate |
onUpdated | updated |
onActivated / onDeactivated | activated / deactivated |
onBeforeUnmount / onUnmounted | beforeUnmount / unmounted |
onErrorCaptured | errorCaptured |
onRenderTracked / onRenderTriggered | renderTracked / renderTriggered |
要点:
- 没有 onBeforeCreate / onCreated——setup 本身就是。
- 必须在 setup 或组合式函数同步执行期间调用(不能放进 setTimeout 回调、async 函数后续代码,否则 Vue 找不到当前组件实例,警告伺候)。
- 一个组件里同一个钩子可以注册多次,都执行。
- 清理副作用放
onUnmounted或onScopeDispose(后者不依赖组件,纯逻辑函数也能用)。
四、组合式函数(Composables)
4.1 约定
// useMousePosition.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useMousePosition() {
const x = ref(0);
const y = ref(0);
const update = e => { x.value = e.pageX; y.value = e.pageY; };
onMounted(() => window.addEventListener('mousemove', update));
onUnmounted(() => window.removeEventListener('mousemove', update));
return { x, y };
}命名规范:use 开头;入参可以是普通值、ref、getter(内部用 toValue 归一,3.3+);返回保持响应式的对象(ref/reactive),不要返回解构后的普通值——那会把响应式弄丢。
4.2 状态共享:单例 vs 每组件独立
// 每组件独立状态:在函数内部创建
export function useCounter() { const n = ref(0); return { n }; }
// 全局单例(模块作用域创建一次)
const n = ref(0);
export function useGlobalCounter() { return { n }; }第二种本质是"轻量 store",跨组件共享用 Pinia 更规范(带 DevTools、SSR、插件体系)。
4.3 异步组合式函数
export async function useUser(id) { // async 的坑:卸载后状态设置可能泄漏
const user = ref(null);
watchEffect(async () => {
user.value = await fetchUser(id.value);
});
return { user };
}async setup 必须配 <Suspense> 才能用(见《内置组件》),普通组件里建议同步 setup + 内部 watchEffect 拉数据。
4.4 常用组合式函数速查
| 函数 | 用途 |
|---|---|
useEventListener(target, event, cb) | 自动绑定/解绑监听 |
useFetch/useAsyncData | 请求 + loading + 错误态 |
useLocalStorage(key, default) | 本地存储双向绑定 |
useDebounceRef(v, delay) | 防抖值 |
useIntersectionObserver | 元素进入视口(懒加载/埋点) |
这些 @vueuse/core 都有成熟实现,别自己造轮子;要造的话按上面的规范造。
五、模板引用(组合式)
<script setup>
import { ref, onMounted, useTemplateRef } from 'vue';
// 经典:ref 名和模板 ref 同名
const inputEl = ref(null);
onMounted(() => inputEl.value.focus());
// 3.5:useTemplateRef 声明式关联
const inputEl2 = useTemplateRef('input'); // 模板里 ref="input"
</script>
<template>
<input ref="inputEl">
<input ref="input">
</template>组件 ref + expose:
// 子组件 defineExpose({ submit })
const formRef = ref(null);
formRef.value?.submit(); // 只能调到 expose 出去的列表场景仍是函数 ref 收集(和选项式一样没有自动数组)。
六、TypeScript 支持总览
6.1 架构
- SFC 类型推导靠编译器:
defineProps、defineEmits、defineModel的类型信息在编译期解析,模板里的类型检查由vue-tsc(跑vue-tsc --noEmit)完成——普通tsc看不懂.vue。 - 选项式 API 的 this 推导有限,能用,但复杂组件建议迁移组合式。
6.2 TS 与组合式 API
<script setup lang="ts">
import { ref, computed, type Ref } from 'vue';
// ref 显式标注(初始化值推不出类型时必须)
const user = ref<User | null>(null);
const count = ref(0); // 自动 number
// reactive
const form = reactive<{ name: string; age: number }>({ name: '', age: 0 });
// computed 类型自动推导
const upper = computed(() => form.name.toUpperCase());
// defineProps 泛型语法(推荐,最简洁)
const props = defineProps<{
id: number;
name?: string; // 可选
onChange: (v: string) => void; // 函数 prop
}>();
// defineEmits 泛型语法
const emit = defineEmits<{
(e: 'change', value: string): void;
(e: 'delete', id: number): void;
}>();
// defineModel
const model = defineModel<string>(); // 可写 ref
const checked = defineModel<boolean>('checked', { default: false });
// useTemplateRef 泛型
const inputEl = useTemplateRef<HTMLInputElement>('input');
</script>泛型组件(3.3+):让组件自身接受类型参数,典型是列表/表格组件:
<script setup lang="ts" generic="T extends { id: number }">
defineProps<{ items: T[]; selected?: T }>();
</script>父组件 <MyList :items="users" /> 时 T 推导为 User。
事件回调的 TS 类型用 defineEmits 的泛型严格声明后,父组件 @change 的处理器参数自动推导,写错编译期就报。
6.3 TS 与选项式 API
import { defineComponent } from 'vue';
export default defineComponent({
data() {
return { count: 0, user: null as User | null }; // 复杂类型要显式断言
},
methods: {
inc(this: { count: number }) { this.count++; } // this 手动标注(不优雅)
},
computed: {
double(): number { return this.count * 2; } // 返回值标注帮助推导
}
});defineComponent 能把选项对象的 this 推导到组件实例,但 data 返回值的复杂类型、this.$refs 的类型经常推不出来,需要断言。结论:新代码用组合式 + 泛型宏;老选项式项目上 vue-tsc 前先修 this 类型,工作量大的话逐步迁移。
七、常见问答
Q:setup 里为什么没有 this?能拿到组件实例吗?
A:setup 在实例初始化前跑。需要实例方法时用 getCurrentInstance()(仅限内部封装,业务代码不要依赖),或把逻辑改成组合式函数。
Q:props 可以解构吗?
A:3.5 起可以,const { id } = defineProps(['id']) 编译为保持响应式的访问。3.4 及之前解构会丢响应式,必须 props.id 或用 toRefs(props)。
Q:watchEffect 里 fetch 发起了两次?
A:依赖在首次执行时收集,如果回调里既读了 a 又改了 b,而 b 又是依赖……检查副作用里的写入。另外 flush 时机(默认 pre)不等于执行次数,看依赖。
Q:组合式函数里创建 computed/watch 需要手动停止吗?
A:组件 setup 里创建的在组件卸载时自动清理;effectScope 里创建的 scope.stop() 时清理;纯模块作用域创建的永不清理(单例 store 的预期行为)。
Q:async setup 怎么用?
A:包 <Suspense>;或者干脆同步 setup + watchEffect 异步拉数,兼容性最好。
Q:Volar / Vue-Official 扩展是干什么的?
A:VS Code 的 Vue 语言支持插件,提供模板类型检查、跳转、补全。装一个就行,别和旧 Vetur 混装。
