Pinia Documentation

website·Indexed 30 days ago

https://pinia-ru.netlify.app

Documentation for Pinia, a Vue.js state management store. Includes guides on core concepts like getters and plugins, SSR (Server-Side Rendering), migration from Vuex ≤4, and a comprehensive API reference covering interfaces such as StoreDefinition, PiniaPlugin, and TestingPinia.

Tokens
25.5K
Snippets
147
Records
194
Agent score
74%

What's inside Pinia

  1. Overview of Pinia state management

    Pinia is a state management library for Vue that allows sharing state between components and pages. It is compatible with both Vue 2 and Vue 3 and does not require the Composition API. While simple reactive objects (export const state = reactive({})) can work for SPAs, Pinia is recommended for Server-Side Rendering (SSR) to prevent cross-request state pollution security vulnerabilities. Key features include:

    • Full TypeScript support and JS autocompletion
    • SSR support
    • Devtools integration (action/mutation timeline, time-travel debugging)
    • Hot Module Replacement (HMR) to preserve state during development
    • Plugin system for extensibility
  2. Use the Pinia root instance to manage stores

    The Pinia instance is the root object for the Pinia state management system. Each Vue application must have its own Pinia instance to enable the creation of stores. It provides a global state property which is a Ref containing a record of all store states (StateTree).
  3. Understand the _SubscriptionCallbackMutationBase interface

    _SubscriptionCallbackMutationBase is an internal base type in Pinia used for the context object passed to subscription callbacks. It provides common metadata about a mutation, such as the store ID and the type of mutation occurring. It serves as the parent interface for more specific mutation types: SubscriptionCallbackMutationDirect, SubscriptionCallbackMutationPatchFunction, and SubscriptionCallbackMutationPatchObject.
  4. Understand Pinia Store concepts

    A store is an entity that holds global state and business logic independent of the component tree. It consists of three core concepts that map to standard Vue component options:

    • State: Equivalent to data.
    • Getters: Equivalent to computed.
    • Actions: Equivalent to methods.
  5. Use TestingPinia for Pinia store testing

    The TestingPinia interface provides a specialized Pinia instance designed for testing environments. It extends the standard Pinia class, inheriting its core functionality while providing a foundation for testing-specific properties and behaviors.
  6. Initialize @pinia/nuxt module in Nuxt configuration

    The @pinia/nuxt module provides a default export function used for module setup within a Nuxt environment. It accepts inlineOptions of type ModuleOptions and the nuxt instance to configure the Pinia store integration.
    // The default export function signature
    export default (this: any, inlineOptions: ModuleOptions, nuxt: Nuxt): _ModuleSetupReturn
  7. Hydrate a Pinia store during SSR

    The hydrate method allows you to manually restore a store's state during Server-Side Rendering (SSR). This is necessary when the state contains complex types (like customRef, computed, or ref) where simply copying the value from pinia.state is insufficient, such as when a ref is linked to local storage.
    const useStore = defineStore('main', {
      state: () => ({
        n: useLocalStorage('key', 0)
      }),
      hydrate(storeState, initialState) {
        // Manually restore the ref-link to local storage
        // @ts-expect-error: https://github.com/microsoft/TypeScript/issues/43826
        storeState.n = useLocalStorage('key', 0)
      }
    })
    
  8. Map store actions to component methods using mapActions

    The mapActions helper allows you to use store actions directly in a component's methods field without using the Composition API (setup()). It creates an object where the keys are the method names in the component and the values are the actual store actions.
    // Example usage in a Vue component
    export default {
      methods: {
        ...mapActions(useStore, ['actionA', 'actionB']),
        // or with a key mapper
        ...mapActions(useStore, { customName: 'actionA' }),
      }
    }
  9. Use Pinia stores in Single Page Applications (SPA) outside components

    In SPAs, useStore() requires the Pinia plugin to be installed via app.use(pinia) before it can be called. If useStore() is called before the Pinia instance is created and attached to the app, it will fail because the instance cannot be automatically injected. The best practice is to defer the store call by placing it inside functions that execute after the app initialization.
    import { useUserStore } from '@/stores/user'
    import { createPinia } from 'pinia';
    import { createApp } from 'vue'
    import App from './App.vue'
    
    // ❌ Fails: called before pinia is created
    // const userStore = useUserStore()
    
    const pinia = createPinia()
    const app = createApp(App)
    app.use(pinia)
    
    // ✅ Works: pinia instance is now active
    const userStore = useUserStore()
  10. Handle Composable hydration in Option stores for SSR

    When using SSR with Option stores, the state() function is not called if an initial state already exists during client-side instantiation. To ensure composables (like useLocalStorage) are correctly initialized on the client, you must define a hydrate(state, initialState) function to manually assign the composable's value to the state.
    import { defineStore } from 'pinia'
    import { useLocalStorage } from '@vueuse/core'
    
    export const useAuthStore = defineStore('auth', {
      state: () => ({
        user: useLocalStorage('pinia/auth/login', 'bob'),
      }),
    
      hydrate(state, initialState) {
        // Ignore initialState and read directly from browser storage
        state.user = useLocalStorage('pinia/auth/login', 'bob')
      },
    })
    
  11. Install Pinia

    Install the pinia package using a package manager. For applications using Vue versions earlier than 2.7, the @vue/composition-api package must also be installed.
    # Using yarn
    yarn add pinia
    
    # Using npm
    npm install pinia