The setup function is where you prepare your component's data and logic in Vue 3. It helps organize your code clearly and makes it easy to use Vue's new features.
Setup function basics in Vue
<script setup> import { ref } from 'vue' // Define reactive data const count = ref(0) // Define a function function increment() { count.value++ } </script> <template> <button @click="increment">Count is: {{ count }}</button> </template>
The <script setup> block is a special Vue 3 syntax that runs the setup function automatically.
Use ref() to create reactive variables that update the UI when changed.
<script setup> import { ref } from 'vue' const message = ref('Hello!') </script> <template> <p>{{ message }}</p> </template>
<script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <template> <button @click="increment">Clicked {{ count }} times</button> </template>
reactive to track an object and update age on button click.<script setup> import { reactive } from 'vue' const user = reactive({ name: 'Anna', age: 25 }) function birthday() { user.age++ } </script> <template> <p>{{ user.name }} is {{ user.age }} years old.</p> <button @click="birthday">Happy Birthday!</button> </template>
This component shows a button with a count. Each click increases the count number. The ref makes the count reactive, so the UI updates automatically.
It also includes an aria-label for accessibility, helping screen readers describe the button.
<script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <template> <button @click="increment" aria-label="Increment count">Count is: {{ count }}</button> </template>
Always import ref or reactive from 'vue' to create reactive data.
Use value to access or change the value inside a ref.
The <script setup> block is simpler and recommended for new Vue 3 components.
The setup function is where you define reactive data and functions in Vue 3.
Use ref for simple reactive variables and reactive for objects.
<script setup> makes writing setup code easier and cleaner.