Managing global state in Vue applications has traditionally been a complex task with Vuex. However, with the advent of Pinia and the Composition API, you can streamline your state management, making your codebase simpler and more intuitive. In this post, we'll demonstrate how Pinia integrates seamlessly with the Composition API to create a powerful and easy-to-use state management solution.
We’ll build a practical To-Do App to showcase how Pinia and the Composition API work together. This example will highlight the benefits of using Pinia with the Composition API for state management in Vue 3 applications.
🛠️ Building a To-Do App with Pinia and the Composition API
Our To-Do app will allow users to add, toggle, and remove tasks. We will use Pinia to manage the state of our tasks, and the Composition API to build our components.
Step 1: Set Up Your Project
Ensure you have a Vue 3 project set up. If you haven’t already, you can create one using the Vue CLI:
npm install -g @vue/cli
vue create my-vue-app
cd my-vue-app
npm install pinia
Step 2: Create the Pinia Store (store/todoStore.js
)
Define a Pinia store to manage the tasks. This store will include actions to add, toggle, and remove tasks.
// store/todoStore.js
import { defineStore } from 'pinia';
export const useTodoStore = defineStore('todo', {
state: () => ({
tasks: [], // Array to store our to-do tasks
}),
actions: {
addTask(task) {
this.tasks.push({ text: task, completed: false });
},
toggleTask(index) {
this.tasks[index].completed = !this.tasks[index].completed;
},
removeTask(index) {
this.tasks.splice(index, 1);
},
},
});
-
state: Holds the
tasks
array to manage our list of to-do items. - actions: Functions to add, toggle, and remove tasks.
Step 3: Build the To-Do Component (components/TodoApp.vue
)
Use the Pinia store within a Vue component to manage and display tasks.
<template>
<div>
<h1>My To-Do List</h1>
<input v-model="newTask" @keyup.enter="addNewTask" placeholder="Add a new task" />
<ul>
<li v-for="(task, index) in todoStore.tasks" :key="index">
<input type="checkbox" v-model="task.completed" @change="toggleTask(index)" />
<span :class="{ completed: task.completed }">{{ task.text }}</span>
<button @click="removeTask(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useTodoStore } from '../store/todoStore';
// Initialize Pinia store
const todoStore = useTodoStore();
// Local state for the new task input
const newTask = ref('');
// Add a new task to the store
function addNewTask() {
if (newTask.value.trim()) {
todoStore.addTask(newTask.value);
newTask.value = '';
}
}
// Toggle task completion status
function toggleTask(index) {
todoStore.toggleTask(index);
}
// Remove a task from the store
function removeTask(index) {
todoStore.removeTask(index);
}
</script>
<style scoped>
.completed {
text-decoration: line-through;
}
</style>
Explanation:
-
Pinia Store Access: The
useTodoStore
hook gives access to the store's state and actions. -
Local State:
newTask
is a local state variable for the input field. -
Methods: Functions to interact with the store (
addNewTask
,toggleTask
,removeTask
). - Reactive Data: Vue's reactivity system automatically updates the UI based on changes to the store.
Step 4: Register Pinia in Your Vue App
Ensure Pinia is registered in your main Vue application file.
main.js
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia); // Register Pinia
app.mount('#app');
🧠 Why Use Pinia + Composition API?
- Modular and Intuitive: Pinia's store is easy to set up and use, while the Composition API provides a clean and modular way to manage component logic.
- Reactivity: Both Pinia and the Composition API are built on Vue’s reactivity system, ensuring that state changes are reflected in the UI seamlessly.
- Simplicity: Pinia’s API is simpler and more straightforward compared to Vuex, making state management less cumbersome.
📚 Key Takeaways
- Pinia offers a modern, lightweight alternative to Vuex, perfectly suited for use with Vue 3’s Composition API.
- The Composition API provides a more flexible and modular approach to building Vue components, making it easier to manage and reuse logic.
- Integrating Pinia with the Composition API results in a cleaner, more maintainable codebase, simplifying state management in Vue 3 applications.
With Pinia and the Composition API, state management in Vue has never been easier. Embrace this powerful combination to streamline your development workflow and build better Vue applications with less effort!
Top comments (1)
Straightforward and efficient demonstration, thank you :)