Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pinia — Global State Management

Pinia — Global State Management

In this chapter you will learn to use Pinia to manage shared data across components and pages, and implement a "favorite articles" feature.


Why Do We Need Global State Management?

So far, data is passed between components via props and emit.

This is sufficient for simple parent-child relationships, but becomes difficult in the following situations:

The pain point of passing props layer by layer: if component A's data needs to reach component D, it must pass through B and C as intermediaries, even though those intermediate components don't need the data themselves.

Pinia is the officially recommended state management library for Vue 3; it provides a global "data center" that any component can read from and write to directly, without passing layer by layer.


Installing and Registering Pinia

If you selected Pinia when creating the project, skip the installation step.

Otherwise:



$ npm install pinia

Register it in main.js:

Example

// File path: src/main.js

import

{

createApp

}

from

'vue'

import

{

createPinia

}

from

'pinia'

import

App from

'./App.vue'

import

router from

'./router'

const

app

=

createApp

(

App

)

// Create and register the Pinia instance

const

pinia

=

createPinia

(

)

app.

use

(

pinia

)

app.

use

(

router

)

app.

mount

(

'#app'

)


defineStore — Defining a Store

The core of Pinia is the Store, and each Store manages a piece of independent state.

It contains three parts:

Section Purpose Analogy
state Store data The component's data / ref
getters Derived computed data The component's computed
actions Methods to modify data The component's methods / function

Example

// File path: src/stores/useFavoriteStore.js

import

{

defineStore

}

from

'pinia'

import

{

ref

,

computed

}

from

'vue'

// defineStore('storeName', () => { ... })

// The second parameter uses a function form, consistent with the Composition API style

export

const

useFavoriteStore

=

defineStore

(

'favorite'

,

(

)

=>

{

 

// ====== state: define state with ref ======

 

// Use an array to store favorited article IDs

 

const

favoriteIds

=

ref

(

[

]

)

 

// Restore the favorite list from localStorage

 

const

saved

=

localStorage.

getItem

(

'blog-favorites'

)

 

if

(

saved

)

{

    favoriteIds.

value

=

JSON.

parse

(

saved

)

 

}

 

// ====== getters: define computed properties with computed ======

 

const

favoriteCount

=

computed

(

(

)

=>

favoriteIds.

value

.

length

)

 

// Determine whether an article is favorited

 

function

isFavorite

(

articleId

)

{

   

return

favoriteIds.

value

.

includes

(

articleId

)

 

}

 

// ====== actions: define modification methods with plain functions ======

 

// Toggle favorite state (favorited → unfavorited, unfavorited → favorited)

 

function

toggleFavorite

(

articleId

)

{

   

const

index

=

favoriteIds.

value

.

indexOf

(

articleId

)

   

if

(

index

===

1

)

{

      favoriteIds.

value

.

push

(

articleId

)

   

// Add to favorites

   

}

else

{

      favoriteIds.

value

.

splice

(

index

,

1

)

   

// Remove from favorites

   

}

   

// Sync to localStorage (persist)

    localStorage.

setItem

(

'blog-favorites'

,

JSON.

stringify

(

favoriteIds.

value

)

)

 

}

 

return

{

favoriteIds

,

favoriteCount

,

isFavorite

,

toggleFavorite

}

}

)

The second parameter of defineStore has two forms:Options Store(similar to Vue 2's data/methods/computed object form) and Setup Store(the Composition API function form). The Setup Store is recommended, as it is exactly the same as the

Add a Favorite Button on the Detail Page Too

Example

The favorite state on the home page and detail page is fully synced: after favoriting an article on the home page, it automatically shows "Favorited" when you enter the detail page.

This is the value of global state management: data is stored only once, and all components read and write from the same source. No emit passing, no layer-by-layer props forwarding.


Display the Favorite Count in NavBar

Display the favorite count on the right side of the navbar; clicking shows the list of favorited articles.

Example

The count in NavBar automatically stays in sync with the latest favorite list — favoriting or unfavoriting an article immediately changes the navbar number.


Summary of Pinia's Three Core Capabilities

Capability Corresponding Code Reflected in the Favorite Feature
Global Sharing Any component can useXxxStore() NavBar, BlogCard, and PostView share the same favorite list
Reactive When state changes, all consumers update automatically After favoriting, the home button turns red, the navbar count +1, and the detail page updates in sync
Persistence Actions write to localStorage The favorite list remains after refreshing the page

Chapter Summary

In this chapter you mastered the complete usage of Pinia global state management: defineStore to define a store (state/getters/actions), useXxxStore to obtain an instance in components, and localStorage for data persistence.

The "favorite articles" feature makes data synchronization between the home page, detail page, and navbar very natural; all components stay consistent automatically.