What is Script Setup in Vue: Simple Explanation and Example
script setup is a special syntax in Vue 3 that lets you write component logic more simply and cleanly inside a single <script setup> block. It automatically handles imports, reactive variables, and component options without extra boilerplate code.How It Works
Imagine you are writing a recipe and want to list ingredients and steps clearly without repeating yourself. script setup works like that for Vue components: it lets you write your component's logic in one place, without extra wrapping or exporting. Vue automatically understands what you write inside the <script setup> block and sets it up for the component.
Normally, Vue components need you to define a setup() function and return the variables or functions you want to use in the template. With script setup, you just declare variables and functions directly, and Vue makes them available in the template automatically. This makes your code shorter and easier to read, like writing a note directly instead of a formal letter.
Example
This example shows a simple Vue component using script setup to create a counter that increases when you click a button.
<template> <button @click="count++">Count is: {{ count }}</button> </template> <script setup> import { ref } from 'vue' const count = ref(0) </script>
When to Use
Use script setup whenever you want to write Vue components with less code and clearer structure. It is great for beginners because it removes the need to learn the setup() function syntax and returning objects.
It is also useful in real projects to keep components clean and easy to maintain. For example, when building UI elements like buttons, forms, or small widgets, script setup helps you focus on the logic without extra ceremony.
Key Points
- Less boilerplate: No need to write
setup()or return statements. - Direct usage: Variables and functions are directly usable in templates.
- Automatic imports: Works well with Vue's reactivity APIs like
refandcomputed. - Recommended for Vue 3: It is the modern, simpler way to write components.
Key Takeaways
script setup simplifies Vue component code by removing extra syntax.