SoFunction
Updated on 2025-04-05

Various detailed descriptions and usage examples of Pinia in Vue

Introduction to Pinia

Pinia is Vue's exclusive state management library designed for Vue 3 and is designed to replace Vuex to provide a simpler and more intuitive state management solution. Pinia is designed to be simple, easy to learn and use, and supports combination and option APIs. It allows sharing state across components or pages, avoiding many complex concepts in Vuex.

Install Pinia

Installing Pinia is very simple and can be done via npm or yarn:

npm install pinia --save
# oryarn add pinia

Create Store

In Pinia, the core of state management is the Store. Store can be understood as an object containing states, getters, and actions. Here is a basic example of creating a Store:

// stores/
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false,
    user: null
  }),
  actions: {
    login(user) {
       = true;
       = user;
    },
    logout() {
       = false;
       = null;
    }
  },
  getters: {
    isUserLoggedIn: (state) => ,
    currentUser: (state) => 
  }
});

Register Store

Register Pinia and Store in the main app file:

// 
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './';
import { useUserStore } from './stores/user';
const app = createApp(App);
// Register Pinia(createPinia());
// Sign up Store('user', useUserStore());
('#app');

Using Store

Using Store in Components is very simple, just need to go throughuseStoreJust get the Store instance by function:

// components/
import { defineComponent } from 'vue';
import { useUserStore } from '@/stores/user';
export default defineComponent({
  setup() {
    const userStore = useUserStore();
    const handleLogin = (user) => {
      (user);
    };
    return {
      userStore,
      handleLogin
    };
  }
});

Multiple Stores

Pinia supports creating multiple stores, each with its own namespace, which allows for better organization of state. For example, you can create a counter Store and a user Store:

// stores/
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      ++;
    },
    decrement() {
      --;
    }
  },
  getters: {
    doubleCount: (state) =>  * 2
  }
});

Advanced use

Extend Pinia with plug-ins

Pinia allows extension of its functionality through plug-ins, such as supporting server-side rendering or adding additional middleware. Here is an example of using a persistent plugin:

import { defineStore } from 'pinia';
import { persist } from 'pinia-plugin-persist';
export const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    count: 0
  }),
  getters: {
    doubleCount: (state) =>  * 2
  },
  actions: {
    increment() {
      ++;
    },
    decrement() {
      --;
    }
  },
  plugins: [persist()]
});

Store's modular design

In actual development, different modules are usually defined as different stores, and then integrated through a root store:

// stores/
import useUserStore from './user';
import useCounterStore from './counter';
export default function useStore() {
  return {
    user: useUserStore(),
    counter: useCounterStore()
  };
}

Responsive state binding to components

Pinia is tightly integrated with Vue’s responsive system, allowing developers to manage state in a declarative manner. For example, it can be used in componentsstoreToRefsTo deconstruct responsive state:

<script setup>
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
const { count, doubleCount } = storeToRefs(counterStore);
</script>

Comprehensive examples

Here is a comprehensive example showing how to use Pinia Store in Vue components, including state, getters, and actions:

// stores/
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  getters: {
    doubleCount: (state) =>  * 2
  },
  actions: {
    increment() {
      ++;
    },
    decrement() {
      --;
    }
  }
});
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>
<script>
import { useCounterStore } from '@/stores/counter';
export default {
  setup() {
    const counterStore = useCounterStore();
    return {
      count: ,
      doubleCount: ,
      increment: ,
      decrement: 
    };
  }
};
</script>

Summarize

Pinia provides a more modern and more Vue 3 Composition API-style state management approach. It simplifies the complexity of state management, allowing developers to focus more on the implementation of business logic. By using Pinia, you can easily achieve efficient state management in your Vue 3 app.

Vuex and Pinia comparison

Design concepts and goals

  • Vuex: Vuex is an officially recommended state management library, originally designed for Vue 2 with the goal of providing a centralized state management solution for Vue applications. It supports modular, thermal reload, strict mode and other functions, and is suitable for large and medium-sized Vue applications.
  • Pinia: Pinia is the official recommended status management library for Vue 3, designed for Vue 3. Inspired by the Vue Composition API and new features of Vue 3, it simplifies many of Vuex's complex concepts and provides a more intuitive and modern API design.

API and syntax

  • Vuex:
    • State: Defines the state of the application.
    • Getters: used to derive states, similar to computed attributes.
    • Mutations: Used to synchronize changes in states.
    • Actions: Used asynchronous operations, can contain multiple mutations.
  • Pinia:
    • State: Defines the state of the application.
    • Getters: used to derive states, similar to computed attributes.
    • Actions: Used for synchronous and asynchronous operations, can contain multiple state changes.
    • Pinia removes Mutations in Vuex, and state modification can be directly modified through actions or state.

Type support

  • Vuex: Although TypeScript is supported, its type derivation may not be as powerful as Pinia.
  • Pinia: Natively supported TypeScript, providing more powerful type derivation and type safety.

Modularity and organization

  • Vuex: supports modularity, which can split state and operation into multiple modules, making it easy to manage and maintain large applications.
  • Pinia: Each store is independent and automatically loads on demand, without the need to register and unregister the module.

Development experience and tool support

  • Vuex: With a rich plug-in ecosystem and mature community support. Provides powerful tools and plug-ins such as Vue Devtools to help debug and analyze applications.
  • Pinia: Although the community is relatively new, the community is growing rapidly. Supports Vue Devtools and provides time travel and status snapshots.

Performance and volume

  • Vuex: More performance optimizations may be required in large applications.
  • Pinia: Smaller size and better performance optimization.

Applicable scenarios

  • Vuex: Suitable for large and complex applications, requiring centralized and strict state management and detailed debugging tools.
  • Pinia: Suitable for small and medium-sized applications, requiring more flexible state management and a more concise API.

Summarize

  • Vuex is a powerful and mature library suitable for scenarios that require strict state management and complex applications.
  • Pinia provides a cleaner API and better TypeScript support, suitable for small and medium-sized applications and scenarios that require more flexible state management.

This is the end of this article about various detailed descriptions and examples of Pinia in Vue. For more information about Vue Pinia, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!