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 …

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores 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.

  1. Create a new file state.js in your src folder.
  2. In state.js, import reactive from vue. reactive is a method provided by Vue that allows us to create a reactive state.
  3. Create a state object using reactive.
  4. 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

  1. Create a state with an array of tasks. Each task should have a title and a boolean indicating if it's done or not.
  2. Create a component that displays all the tasks and their status.
  3. Create another component that allows you to add new tasks.

Solution:

  1. The state.js file:
import { reactive } from 'vue'

const state = reactive({
  tasks: []
})

export function useGlobalState() {
  return state
}
  1. 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>
  1. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help