SoFunction
Updated on 2025-04-05

Vue's new state management library Pinia tutorial

Why has Pinia become popular recently? It is mainly because when Vue3 was launched, Vuex did not support Vue3's combination API, which was at this time Pinia appeared.

cutting edge

The state management library recommended by Vue is Vuex. Why has Pinia become popular recently? It is mainly because when Vue3 was launched, Vuex did not support Vue3's combination API, which was also very good. At this time, Pinia appeared. The most important thing is that Pinia not only supports Vue3, but also supports Vue2. This is amazing, and the latest Vuex5 features are still referenced.

Usage tutorial

Official website:/

Github address:/vuejs/pinia

1. Installation

npm install pinia -S

2. Introduced in vue

// Introduced and used in Vue3import { createPinia } from 'pinia'

(createPinia())


//Introduced and used in Vue2import { createPinia, PiniaVuePlugin } from 'pinia'

(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  el: '#app',
  // Other configuration items  pinia,
})

3. Basic use

// Define store// stores/
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  // Status value definition  state: () => {
    return { count: 0 }
  },
  // Definition of state change method  actions: {
    increment() {
      ++
    },
  },
})

// Use in components// Import statusimport { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    // Initialize a store instance    const counter = useCounterStore()

    // state update    ++
    
    // Or call method update    ()
  },
}

4. It can also be used like vuex

const useCounterStore = defineStore('counter', {
  // Status value  state: () => ({ count: 0 }),
  // getter value  getters: {
    double: (state) =>  * 2,
  },
  // actions method  // Note that there is no mutation in pinia  actions: {
    increment() {
      ++
    }
  }
})

// Define another storeconst useUserStore = defineStore('user', {
  // ...
})

export default {
  // Incoming the value in state is introduced using the value in the computer  computed: {
    ...mapStores(useCounterStore, useUserStore)
    ...mapState(useCounterStore, ['count', 'double']),
  },
  // Use action in methods  methods: {
    ...mapActions(useCounterStore, ['increment']),
  },
}

Okay, this is all about Pinia's introductory tutorial. Is the grammar more concise?

This is the article about the introduction to the new Vue status management library Pinia tutorial. For more related Vue Pinia content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!