Introduction
Vue 3 has introduced the Composition API, a powerful tool to enhance the way developers build reactive applications. By allowing a more flexible organization of component logic, it provides a streamlined approach to developing complex user interfaces.
Getting Started
To kick off your Vue 3 project, start by setting up your development environment:
npm create vue@latest my-app
cd my-app
npm install && npm run dev
This sequence of commands initializes a new Vue 3 application, installs necessary packages, and starts a development server.
Understanding the Composition API
The Composition API allows you to manage your component logic more effectively. Here's a basic example highlighting its usage:
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
const count = ref(0);
const doubled = computed(() => count.value * 2);
function increment() {
count.value++;
}
onMounted(() => {
console.log("Component mounted!");
});
</script>
<template>
<p>Count: {{ count }} (doubled: {{ doubled }})</p>
<button @click="increment">+1</button>
</template>
Key Features
- Reactivity Primitives: Use reactive and ref to manage state.
- Lifecycle Hooks: Utilize onMounted for side-effects when the component is rendered.
Managing Reactive State
Vue 3 provides tools to handle state reactively, allowing dynamic updates to your UI. Here's how you can manage a simple to-do list:
<script setup>
import { reactive, toRefs } from "vue";
const state = reactive({
todos: [],
filter: "all",
newTodo: ""
});
const { todos, filter, newTodo } = toRefs(state);
function addTodo() {
state.todos.push({ id: Date.now(), text: state.newTodo, done: false });
state.newTodo = "";
}
const filteredTodos = computed(() => {
if (state.filter === "done") return state.todos.filter(t => t.done);
if (state.filter === "active") return state.todos.filter(t => !t.done);
return state.todos;
});
</script>
This setup effectively manages the state and renders only the relevant tasks based on the filter.
Creating Custom Composables
Custom hooks or composables can encapsulate reusable logic:
// composables/useFetch.ts
import { ref, watchEffect } from "vue";
export function useFetch<T>(url: string) {
const data = ref<T | null>(null);
const error = ref<Error | null>(null);
const loading = ref(true);
watchEffect(async () => {
loading.value = true;
try {
const res = await fetch(url);
data.value = await res.json();
} catch (e) {
error.value = e as Error;
} finally {
loading.value = false;
}
});
return { data, error, loading };
}
These composables can be imported and used throughout your application to fetch data or implement other logic.
Handling Props and Events
Vue 3 simplifies the handling of props and events:
<script setup lang="ts">
const props = defineProps<{
title: string;
count?: number;
}>();
const emit = defineEmits<{
(e: "update", value: number): void;
(e: "delete"): void;
}>();
</script>
This structure ensures that components remain highly configurable and interactive.
Utilizing Watchers
Watchers in Vue 3 can react to changes in data:
<script setup>
import { watch, watchEffect } from "vue";
watch(count, (newVal, oldVal) => {
console.log(`Changed from ${oldVal} to ${newVal}`);
});
watchEffect(() => {
document.title = `Count: ${count.value}`;
});
</script>
These tools are crucial for dynamic applications where real-time data updates are necessary.
Conclusion
The Composition API in Vue 3 offers a modern, scalable approach to developing complex applications. By leveraging its features such as reactive state management, lifecycle hooks, and composables, developers can create powerful, efficient UIs with ease.