<script setup>
<script setup> is a compile-time syntactic sugar for using Composition API inside Single-File Components (SFCs).
Basic Syntax
Key Features
Top-Level Bindings Auto-Exposure
All top-level bindings (variables, functions, imports) are automatically exposed to the template:Automatic Ref Unwrapping
Refs are automatically unwrapped in templates (no need for.value):
Top-Level Await
<script setup> supports top-level await. The component will be set up as an async dependency:
Suspense:
Compiler Macros
These macros are globally available without imports and are compiled away:defineProps()
Declare component props:Props Destructure (Vue 3.5+)
Destructure props while maintaining reactivity:- Are transformed to maintain reactivity
- Support default values in destructuring
- Can be used directly in reactive APIs
- Are compiled to efficient code
defineEmits()
Declare component events:defineExpose()
Explicitly expose properties to parent via template refs:defineModel()
Declare two-way binding props (Vue 3.4+):defineSlots()
Type-check and get IntelliSense for slots (TypeScript only):defineOptions()
Define component options that can’t be expressed in<script setup>:
TypeScript Support
Generic Components
Define generic type parameters:Type-Only Props
Import types for props:- Extract runtime prop types for type-based declarations
- Support imported types from external files
- Maintain type safety throughout the component
Usage with Normal <script>
Combine with a normal <script> block for:
- Options not expressible in
<script setup>(e.g., plugins) - Named exports
- Side effects that run once
Restrictions
Cannot Use src
<script setup> cannot use the src attribute:
No Default Export
Do not use default export in<script setup>:
defineOptions() instead for component options.
Script Position
When used with normal<script>, <script setup> should come after:
Build Optimizations
Static Hoisting
Static content is automatically hoisted outside the render function:Tree-Shaking
Unused imports are automatically tree-shaken:Import Usage Check
For TypeScript SFCs, imports are checked for template usage:- Type-only imports not used in template are preserved
- Component imports not used in template are removed
- This enables HMR optimization
Compilation Output
A<script setup> component: