The script setup syntax in Vue makes writing components simpler and cleaner by reducing extra code and boilerplate.
0
0
Script setup syntax in Vue
Introduction
When you want to write Vue components with less code and easier readability.
When you want to use Composition API features without importing and returning everything manually.
When building small to medium components quickly with clear structure.
When you want better TypeScript support with less setup.
When you want to avoid the usual <code>export default</code> block and simplify component logic.
Syntax
Vue
<script setup> import { ref } from 'vue' // Your component logic here const count = ref(0) function increment() { count.value++ } </script>
You do not need to write
export default in script setup.Variables and functions declared here are directly usable in the template.
Examples
Basic example showing a reactive variable used in the template.
Vue
<script setup> import { ref } from 'vue' const message = ref('Hello!') </script> <template> <p>{{ message }}</p> </template>
Example with a reactive counter and a function to update it.
Vue
<script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <template> <button @click="increment">Clicked {{ count }} times</button> </template>
Using TypeScript with
script setup for type safety.Vue
<script setup lang="ts"> import { ref, type Ref } from 'vue' const name: Ref<string> = ref('Vue') </script> <template> <h1>Hello, {{ name }}</h1> </template>
Sample Program
This Vue component uses script setup to create a simple button that counts clicks. The count variable is reactive and updates the displayed number each time the button is clicked. The button includes an accessible label for screen readers.
Vue
<script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <template> <button @click="increment" aria-label="Increment counter"> Clicked {{ count }} times </button> </template>
OutputSuccess
Important Notes
All top-level variables and functions in script setup are automatically exposed to the template.
You can import other modules normally inside script setup.
Use lang="ts" attribute for TypeScript support.
Summary
Script setup simplifies Vue component code by removing the need for export default.
Reactive variables and functions are directly usable in the template.
It supports TypeScript and improves readability for Composition API usage.