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

Pinia Getting Started Tutorial

Pinia Getting Started Tutorial

In Vue 3, state management is an unavoidable topic.

Pinia is a lightweight state management library for Vue.js that lets you share and manage state between components. We can think of Pinia as a global data warehouse from which all components can fetch or update data.

In this chapter we introduce Pinia, the state management library officially recommended for Vue 3. Compared with Vuex, Pinia provides a simpler state management solution that better fits Vue 3's Composition API mindset.

The diagram below compares the structural differences between the two:

Pinia core features:

Pinia's flat structure lets components connect directly to any store, taking only what they need—without going through tree-shaped modules or namespace paths—making state flow simple and direct with low coupling.


Installation and Configuration

Create a project with Vite:

npm create vite@latest vue-pinia-demo --template vue

cd vue-pinia-demo

npm install

Install Pinia

First, install Pinia in your Vue 3 project:



npm install pinia

# 或者

yarn add pinia

Pinia has three parts:

Configure Pinia

Configure Pinia in src/main.js or src/main.ts:

Example

// main.js

import

{

createApp

}

from

'vue'

import

{

createPinia

}

from

'pinia'

import

App from

'./App.vue'

// create the Pinia instance

const

pinia

=

createPinia

(

)

// create the Vue application

const

app

=

createApp

(

App

)

// use Pinia

app.

use

(

pinia

)

app.

mount

(

'#app'

)


Create the First Store

A Store is Pinia's data warehouse; let's create a simple counter Store.

Define a Store

Create a new src/stores/useCounter.js:

Example

// stores/useCounter.js

import

{

defineStore

}

from

'pinia'

// define the store with defineStore

// the first argument is the store's unique ID

// the second argument is the store's configuration options

export

const

useCounterStore

=

defineStore

(

'counter'

,

{

 

// state: define the store's state data

  state

:

(

)

=>

(

{

    count

:

0

,

    name

:

'My Counter'

 

}

)

,

 

// getters: define computed properties based on state

  getters

:

{

    doubleCount

:

(

state

)

=>

state.

count

2

,

   

// use this to access other getters

    doubleCountPlusOne

(

)

{

     

return

this

.

doubleCount

1

   

}

 

}

,

 

// actions: define methods that modify state

  actions

:

{

    increment

(

)

{

     

this

.

count

++

   

}

,

    decrement

(

)

{

     

this

.

count

--

   

}

,

   

// can accept parameters

    incrementBy

(

amount

)

{

     

this

.

count

+=

amount

   

}

,

   

// async action

    async incrementAsync

(

)

{

     

// simulate an async operation

      await

new

Promise

(

resolve

=>

setTimeout

(

resolve

,

1000

)

)

     

this

.

count

++

   

}

 

}

}

)

Store Structure Explanation

Let's understand each part of the Store through a table:

Section Purpose Example
state Defines the stored data count: 0
getters Computed properties based on state doubleCount: state => state.count * 2
actions Methods to modify state increment() { this.count++ }

Using a Store in a Component

Basic Usage

The code for src/components/CounterComponent.vue is as follows:

Example

Modify src/App.vue with the following code:

Example

The overall project structure:

Run the npm run dev command and visit in the browser http://localhost:5173/, to see the effect:

Reactive Destructuring

If you want to use state properties directly in the template, you can use storeToRefs:

Example


Composition API Style Store

Pinia also supports defining stores using the Composition API style:

Example

// stores/user.js

import

{

defineStore

}

from

'pinia'

import

{

ref

,

computed

}

from

'vue'

export

const

useUserStore

=

defineStore

(

'user'

,

(

)

=>

{

 

// state

 

const

user

=

ref

(

null

)

 

const

isLoggedIn

=

ref

(

false

)

 

// getters

 

const

userName

=

computed

(

(

)

=>

user.

value

?

.

name

||

'Guest'

)

 

const

userAge

=

computed

(

(

)

=>

user.

value

?

.

age

||

0

)

 

// actions

 

function

login

(

userData

)

{

    user.

value

=

userData

    isLoggedIn.

value

=

true

 

}

 

function

logout

(

)

{

    user.

value

=

null

    isLoggedIn.

value

=

false

 

}

 

return

{

    user

,

    isLoggedIn

,

    userName

,

    userAge

,

    login

,

    logout

 

}

}

)


Interaction Between Stores

Multiple stores can call each other:

Example

// stores/cart.js

import

{

defineStore

}

from

'pinia'

import

{

useUserStore

}

from

'./user'

export

const

useCartStore

=

defineStore

(

'cart'

,

{

  state

:

(

)

=>

(

{

    items

:

[

]

 

}

)

,

  actions

:

{

    addItem

(

product

)

{

     

this

.

items

.

push

(

product

)

     

     

// call another store's action

     

const

userStore

=

useUserStore

(

)

     

if

(

userStore.

isLoggedIn

)

{

       

// sync to the user's cart

       

this

.

syncToUserCart

(

)

     

}

   

}

 

}

}

)


Practical Example: Shopping Cart

Let's create a complete shopping cart example:

Example

// stores/products.js

export

const

useProductStore

=

defineStore

(

'products'

,

{

  state

:

(

)

=>

(

{

    products

:

[

     

{

id

:

1

,

name

:

'Laptop'

,

price

:

5999

,

stock

:

10

}

,

     

{

id

:

2

,

name

:

'Smartphone'

,

price

:

3999

,

stock

:

20

}

,

     

{

id

:

3

,

name

:

'Wireless Earbuds'

,

price

:

299

,

stock

:

50

}

   

]

 

}

)

,

  getters

:

{

   

// get product by ID

    getProductById

:

(

state

)

=>

(

id

)

=>

{

     

return

state.

products

.

find

(

product

=>

product.

id

===

id

)

   

}

,

   

// get products in stock

    availableProducts

:

(

state

)

=>

{

     

return

state.

products

.

filter

(

product

=>

product.

stock

0

)

   

}

 

}

}

)

Example

// stores/cart.js

export

const

useCartStore

=

defineStore

(

'cart'

,

{

  state

:

(

)

=>

(

{

    items

:

[

]

,

// { productId, quantity }

    discount

:

0

 

}

)

,

  getters

:

{

   

// total number of items in cart

    totalItems

:

(

state

)

=>

{

     

return

state.

items

.

reduce

(

(

total

,

item

)

=>

total

item.

quantity

,

0

)

   

}

,

   

// total amount of the cart

    totalPrice

:

(

state

)

=>

{

     

const

productStore

=

useProductStore

(

)

     

return

state.

items

.

reduce

(

(

total

,

item

)

=>

{

       

const

product

=

productStore.

getProductById

(

item.

productId

)

       

return

total

(

product

?

.

price

||

0

)

item.

quantity

     

}

,

0

)

   

}

,

   

// total price after discount

    finalPrice

:

(

state

)

=>

{

     

return

state.

totalPrice

(

1

state.

discount

/

100

)

   

}

 

}

,

  actions

:

{

   

// add product to cart

    addToCart

(

productId

,

quantity

=

1

)

{

     

const

existingItem

=

this

.

items

.

find

(

item

=>

item.

productId

===

productId

)

     

     

if

(

existingItem

)

{

        existingItem.

quantity

+=

quantity

     

}

else

{

       

this

.

items

.

push

(

{

productId

,

quantity

}

)

     

}

   

}

,

   

// remove product from cart

    removeFromCart

(

productId

)

{

     

this

.

items

=

this

.

items

.

filter

(

item

=>

item.

productId

!==

productId

)

   

}

,

   

// clear the cart

    clearCart

(

)

{

     

this

.

items

=

[

]

     

this

.

discount

=

0

   

}

,

   

// set discount

    setDiscount

(

percent

)

{

     

this

.

discount

=

Math

.

max

(

0

,

Math

.

min

(

100

,

percent

)

)

   

}

 

}

}

)

Using the Cart in a Component

Example