tezvyn:

Vue's <script setup>: Less Boilerplate, More Performance

AI-drafted, machine-checkedSource: vuejs.orgintermediate

Vue's <script setup> is compile-time sugar that automatically exposes variables and functions to your template, cutting boilerplate. It yields more succinct, performant components with better type-safety.

WHY IT EXISTS The standard Composition API setup() function requires you to explicitly return every variable, function, or component that the template needs. This is verbose and separates declaration from exposure. <script setup> was created to eliminate this boilerplate by making the script's top-level scope directly and automatically available to the template.

THE MENTAL MODEL Think of the <script setup> block as the body of a traditional setup() function, but with an implicit return for everything declared at the top level. Variables, imported components, and helper functions are all automatically available to the template, just as if they were in the same file.

HOW IT WORKS By adding the setup attribute to a <script> tag, you instruct the Vue compiler to process it differently. It analyzes the block and makes all top-level bindings (variables, functions, imports) available to the template's compiled render function. This direct binding is more performant than the proxy-based access used in the standard setup() or Options API. Special functions like defineProps and defineEmits, known as compiler macros, are globally available inside <script setup>. They are processed at compile time to define component interfaces and don't need to be imported.

WHEN TO USE IT Use <script setup> for all new Vue Single-File Components (SFCs). It is the modern, recommended approach for writing components with the Composition API. It is especially powerful when combined with TypeScript, as it provides excellent type inference for props and emits with minimal ceremony.

WHEN NOT TO USE IT Avoid it if you must use the Options API for a specific component. The most common footgun is needing code to run only once when the component's module is first imported. For that, you can use a separate, normal <script> block in the same file alongside the <script setup> block, as the <script setup> code runs for every new component instance.

ONE CANONICAL EXAMPLE A simple counter. Traditionally, you would write: import { ref } from 'vue'; export default { setup() { const count = ref(0); return { count }; } }. With <script setup>, this becomes much cleaner: import { ref } from 'vue'; const count = ref(0);. The template <button @click="count++">{{ count }}</button> can then directly access count without any explicit return statement.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.