script setup 是 Vue 3 推出的 SFC 专用写法:只要在 script 标签上加 setup 属性,整个代码块就自动成为 setup 函数体,顶层声明的变量、函数、import 进来的组件无需 return 就能在模板里直接使用。defineProps、defineEmits 等宏由编译器注入,运行时没有额外开销。
相比普通 setup 函数写法,它省掉了 return 模板变量、注册子组件等样板代码,TypeScript 对 props 的类型推导也更完整,还能享受编辑器的模板自动补全。它也能与普通 script 标签并存,用来放 name、inheritAttrs 等额外选项。新项目应默认使用它,可复用逻辑仍可拆成独立 composables。
<template> <button @click="count++">点击 {{ count }} 次</button> </template> <script setup> import { ref } from 'vue'; import MyChild from './MyChild.vue'; const count = ref(0); const props = defineProps({ title: String }); const emit = defineEmits(['close']); </script> <style scoped> button { color: #4a9eff; } </style>