## Vue Composition API: The `setup` Function
The `setup` function is the heart of the Composition API in Vue 3. It's a new option that's added to a component, and it's where you define reactive state, computed properties, methods, and lifecycle hooks. It replaces the `data`, `methods`, `computed`, and `watch` options found in the Options API.
**Why `setup`?**
* **Logic Reusability:** Easily extract and reuse component logic into composable functions.
* **Better Organization:** Group related logic together, improving code readability and maintainability, especially in larger components.
* **Type Inference:** Works seamlessly with TypeScript, providing strong typing and improved developer experience.
* **Flexibility:** Offers more control over how component logic is structured and managed.
* **Tree-shaking:** Allows unused code to be removed during the build process, resulting in smaller bundle sizes.
**Basic Structure**
```vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
// 1. Reactive State
const count = ref(0);
// 2. Methods
const increment = () => {
count.value++;
};
// 3. Return Values - Make them available to the template
return {
count,
increment
};
}
};
</script>
Explanation:
setup()Function: This function is executed before the component is created. It's where you define all your component logic.ref(): Theref()function from Vue creates a reactive reference. Any changes tocount.valuewill automatically trigger updates in the template.refis used for primitive types (numbers, strings, booleans) and objects.increment(): A regular JavaScript function that updates the reactivecountvariable.return: Crucially, you must return an object from thesetupfunction. The properties of this object are exposed to the template. In this example, we're returningcountandincrement, making them accessible in the template as{{ count }}and@click="increment".
Key Concepts & APIs within setup
ref(): Creates a reactive reference for primitive types and objects. Access and modify the value using.value.reactive(): Creates a deeply reactive object. Use this for objects and arrays. Access properties directly (e.g.,myObject.property).computed(): Creates a computed property. It automatically re-evaluates when its dependencies change.watch(): Watches a reactive value and executes a callback function when it changes.watchEffect(): Watches reactive dependencies and automatically runs a function whenever they change. It doesn't require explicitly listing dependencies.provide/inject: Allows components to share data without passing props down through the component tree.- Lifecycle Hooks: Access lifecycle hooks like
onMounted,onUpdated,onUnmounteddirectly from the Vue package. They are now functions, not options.
Example: Using reactive and computed
<template>
<div>
<p>First Name: {{ person.firstName }}</p>
<p>Last Name: {{ person.lastName }}</p>
<p>Full Name: {{ fullName }}</p>
<button @click="updateLastName">Update Last Name</button>
</div>
</template>
<script>
import { reactive, computed } from 'vue';
export default {
setup() {
const person = reactive({
firstName: 'John',
lastName: 'Doe'
});
const fullName = computed(() => {
return person.firstName + ' ' + person.lastName;
});
const updateLastName = () => {
person.lastName = 'Smith';
};
return {
person,
fullName,
updateLastName
};
}
};
</script>
Example: Using Lifecycle Hooks
<template>
<div>
<p>Component is mounted!</p>
</div>
</template>
<script>
import { onMounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log('Component mounted!');
// Perform actions after the component is mounted
});
return {};
}
};
</script>
Composables
Composable functions are reusable pieces of logic that you can extract from your components and use in multiple places. They help to keep your components clean and focused.
// composables/useCounter.js
import { ref } from 'vue';
export function useCounter(initialValue = 0) {
const count = ref(initialValue);
const increment = () => {
count.value++;
};
const decrement = () => {
count.value--;
};
return {
count,
increment,
decrement
};
}
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script>
import { useCounter } from './composables/useCounter';
export default {
setup() {
const { count, increment, decrement } = useCounter(10);
return {
count,
increment,
decrement
};
}
};
</script>
In Summary:
The setup function is a powerful tool for building Vue components with the Composition API. It provides a more flexible, organized, and reusable way to manage component logic, especially as your applications grow in complexity. Understanding ref, reactive, computed, watch, and lifecycle hooks within the context of setup is essential for mastering the Composition API.
```