Top

State Management with Pinia


In a large Vue 3 application, you often need to share data across multiple components or pages. These shared variables must be reactive, so when the value changes in one place, it updates automatically everywhere else. In Vue, the recommended way to manage global state is with Pinia.

Setting up Pinia

Install Pinia in your project:

npm install pinia

In Vue, you can enable Pinia by adding the official module in your main.ts:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')
Creating a Store

Create a new store inside the src/stores folder. For example:

// src/stores/useExampleStore.ts
import { defineStore } from 'pinia'

export const useExampleStore = defineStore('example', () => {
  // state
  const variable1 = ref(false)

  // actions
  function toggleVariable() {
    variable1.value = !variable1.value
  }

  return {
    variable1,
    toggleVariable
  }
})

This store can now be accessed globally from any page or component.

Using a Store in a Component

To use the store, import it and access its state or actions directly:

<script setup lang="ts">
import { useExampleStore } from '@/stores/useExampleStore'

const example = storeToRefs(useExampleStore())

function enableVariable() {
  example.variable1 = true
}
</script>

<template>
  <div>
    <p>Variable value: {{ example.variable1 }}</p>
    <button @click="enableVariable">Enable Variable</button>
  </div>
</template>

Now, whenever variable1 changes in one component, the updated value will be reflected everywhere the store is used.