标准答案
- script setup 会在编译阶段转换成组件的 setup 函数。顶层声明的变量、函数、import 的组件都可以直接在模板中使用。
- defineProps、defineEmits、defineExpose、defineOptions、defineModel 是编译器宏,不需要从 vue 中导入。
- 相比普通 setup,script setup 模板使用更简洁,TypeScript 推导更直接,组件引入后也不用再写 components 注册。
- script setup 中的代码会按组件实例执行。不要把每个实例都不该重复创建的重对象放在里面,模块级常量可以放到 script 外部或普通模块里。
- 需要显式暴露给父组件 ref 调用的能力时,要用 defineExpose。script setup 默认不会把内部变量全部暴露到组件实例上。
题目解析
script setup 的重点是编译期能力,不是运行时新增了一套组件模型。
宏只能在合适的顶层位置使用,不能把 defineProps 放进普通函数或条件分支里。
普通 script 和 script setup 可以同时存在,普通 script 更适合声明只执行一次的模块级选项或副作用。
代码示例
这个例子展示 props、emits 和模板顶层绑定的常见写法。
Vue
<script setup lang="ts">
const props = defineProps<{
title: string
count: number
}>()
const emit = defineEmits<{
increment: []
}>()
function handleClick() {
emit('increment')
}
</script>
<template>
<section>
<h2>{{ props.title }}</h2>
<button type="button" @click="handleClick">
{{ props.count }}
</button>
</section>
</template>常见误区
- 把 defineProps 当成普通运行时函数,在条件语句里调用。
- 在 script setup 里忘记 defineExpose,导致父组件拿不到期望暴露的方法。
- 认为 script setup 会改变组件生命周期。它仍然对应组件实例的 setup 执行阶段。