Skip to content

Setup Store Standard

13.1.1. Pinia Usage Principles

  • Pinia must be used for state management. Vuex must not be used.
  • The Setup Store syntax must be used. The Options Store syntax must not be used.
  • Store files must be placed in the src/stores/ directory.
  • File names must follow the use{Domain}Store.ts pattern.

13.1.2. Setup Store Structure

A Setup Store is written in the same manner as the Composition API's setup() function.

  • ref() -> state
  • computed() -> getters
  • function -> actions
typescript
// src/stores/useUserStore.ts
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { fetchCurrentUser } from '@/api/user'
import type { User } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  // state
  const user = ref<User | null>(null)
  const loading = ref(false)

  // getters
  const isLoggedIn = computed(() => user.value !== null)
  const displayName = computed(() => user.value?.name ?? 'Guest')

  // actions
  async function loadCurrentUser() {
    loading.value = true
    try {
      user.value = await fetchCurrentUser()
    } finally {
      loading.value = false
    }
  }

  function logout() {
    user.value = null
  }

  return { user, loading, isLoggedIn, displayName, loadCurrentUser, logout }
})

13.1.3. Store Initialization

  • The Pinia instance must be created in main.ts and registered with the Vue app.
  • Initial data loading required at app startup must be performed in App.vue's onMounted.
typescript
// src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.mount('#app')

13.1.4. Store Usage Principles

  • Only state that must be shared globally should be placed in a Store.
  • Component-local state must be managed with ref/reactive.
  • Direct references between Stores should be minimized.
State TypeManagement MethodExample
Global statePinia StoreLogged-in user, permissions, theme settings
Page stateComponent refForm inputs, loading state, modal visibility
Server stateComposableAPI response data, pagination

TIENIPIA QUALIFIED STANDARD