Vue.js / Vue Composition API
State Management with Composition API
This tutorial will guide you through managing global state with the Composition API. You'll learn how to create a state that can be accessed and manipulated from any component in …
Section overview
5 resourcesExplores Vue 3's Composition API for structuring applications.
Introduction
Goal of the Tutorial
This tutorial aims to guide you on how to manage global state with the Composition API in Vue.js. This is a crucial aspect of Vue.js as it allows you to create a state that can be accessed and manipulated from any component in your application.
Learning Outcomes
By the end of this tutorial, you will be able to:
- Understand the basic concepts of the Composition API
- Create and manage a global state using the Composition API
- Manipulate the state from any component
Prerequisites
You should have a basic knowledge of Vue.js and JavaScript. Familiarity with ES6+ features, like destructuring and spread operator, would be helpful but not mandatory.
Step-by-Step Guide
Understanding the Composition API
The Composition API is a set of additive, function-based APIs that allows flexible composition of component logic. It's a new way of defining components and managing their state. Instead of using options like data, methods, computed, watch, etc., you use JavaScript functions.
Creating a Global State with the Composition API
The first step is to create a state that can be shared across components. We can do this by creating a new file that will contain our state.
- Create a new file
state.jsin yoursrcfolder. - In
state.js, importreactivefromvue.reactiveis a method provided by Vue that allows us to create a reactive state. - Create a state object using
reactive. - Export a function that returns the state.
Here's how your state.js file should look:
import { reactive } from 'vue'
const state = reactive({
count: 0
})
export function useGlobalState() {
return state
}
Code Examples
Accessing and manipulating the state
You can now use this state in any component you want. Here's an example with two components that share the same state.
Component 1:
<template>
<button @click="increment">Increment</button>
</template>
<script>
import { useGlobalState } from './state'
export default {
setup() {
const state = useGlobalState()
function increment() {
state.count++
}
return {
increment
}
}
}
</script>
In this component, we import our global state and use it in the setup function. We then define a new function increment that increases the count of our state. This function is returned from the setup function and can be used in our template.
Component 2:
<template>
<p>The count is: {{ count }}</p>
</template>
<script>
import { useGlobalState } from './state'
export default {
setup() {
const state = useGlobalState()
return {
count: state.count
}
}
}
</script>
In this component, we also use our global state. However, instead of changing the state, we display its count in the template.
Summary
In this tutorial, we learned about the Composition API and how to create a global state. We then used this state in two different components and saw how changes in one component affect the other.
Next Steps
You can further practice this by creating more complex states and components that manipulate this state.
Additional Resources
Practice Exercises
- Create a state with an array of tasks. Each task should have a title and a boolean indicating if it's done or not.
- Create a component that displays all the tasks and their status.
- Create another component that allows you to add new tasks.
Solution:
- The
state.jsfile:
import { reactive } from 'vue'
const state = reactive({
tasks: []
})
export function useGlobalState() {
return state
}
- The component that displays the tasks:
<template>
<div v-for="task in tasks" :key="task.title">
<p>{{ task.title }} is {{ task.isDone ? 'done' : 'not done' }}</p>
</div>
</template>
<script>
import { useGlobalState } from './state'
export default {
setup() {
const state = useGlobalState()
return {
tasks: state.tasks
}
}
}
</script>
- The component that allows you to add new tasks:
<template>
<input v-model="title" placeholder="New task">
<button @click="addTask">Add</button>
</template>
<script>
import { useGlobalState } from './state'
export default {
setup() {
const state = useGlobalState()
const title = ''
function addTask() {
state.tasks.push({ title, isDone: false })
}
return {
title,
addTask
}
}
}
</script>
In this exercise, we created a more complex state and two components that interact with this state. This is a great way to practice your understanding of managing a global state with the Composition API.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article