💚 Vue.js Advanced

What is Vue 3 script setup deep dive?

Answer

<script setup> is compile-time syntactic sugar for Composition API that reduces boilerplate. Deep understanding: Compiler transformations: <script setup> is compiled into a setup(props, ctx) function. Top-level variables become the setup() return value (automatically exposed to template). Imports are preserved at module scope. Top-level await: const data = await fetchData() at top level creates an async setup component that participates in Suspense boundaries. Compiler macros: defineProps, defineEmits, defineExpose, defineOptions, defineModel, withDefaults — these are NOT imported functions; they are compile-time macros that are removed during compilation and replaced with the appropriate setup() code. defineOptions (Vue 3.3+): set component options not expressible in script setup: defineOptions({ name: "MyComponent", inheritAttrs: false });. defineModel (Vue 3.4+): creates a two-way binding signal: const count = defineModel<number>({ default: 0 }); count.value++; — compiles to modelValue prop + update:modelValue emit. useAttrs / useSlots / useTemplateRef (Vue 3.5+): reactive access to $attrs and $slots inside setup. Generic components (TypeScript): <script setup lang="ts" generic="T"> defineProps<{ items: T[] }>(); </script>. Module exports: named exports in <script setup> are module-level (not component instance level); const/function/class are instance-level (returned by setup). To export module-level: use a separate <script> block alongside <script setup>.