Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Plugins i Persistence

System backupów NOVA LAB zapewnia, że krytyczne dane przetrwają nawet restart stacji. W Pinia tę rolę pełnią plugins - rozszerzenia dodające nowe możliwości do stores. Najważniejszy z nich to persistence - zapisywanie state do localStorage.

$subscribe - nasłuchiwanie zmian

$subscribe
pozwala reagować na każdą zmianę state:

1const store = useResourceStore()
2
3store.$subscribe((mutation, state) => {
4  console.log('Store changed:', mutation.storeId)
5  console.log('Type:', mutation.type) // 'direct' | '$patch'
6  console.log('New state:', state)
7
8  // Automatyczny zapis do localStorage
9  localStorage.setItem('resources', JSON.stringify(state))
10})

Opcje subscribe:

1store.$subscribe(
2  (mutation, state) => { /* ... */ },
3  { detached: true } // Przetrwa unmount komponentu
4)

$onAction - obserwowanie akcji

1const store = useResourceStore()
2
3store.$onAction(({ name, args, after, onError }) => {
4  console.log(`Action started: ${name}`, args)
5
6  after((result) => {
7    console.log(`Action ${name} completed`, result)
8  })
9
10  onError((error) => {
11    console.error(`Action ${name} failed`, error)
12  })
13})

Plugin persistence

Najpopularniejszy plugin -

pinia-plugin-persistedstate
:

1npm install pinia-plugin-persistedstate

Konfiguracja:

1// main.js
2import { createPinia } from 'pinia'
3import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
4
5const pinia = createPinia()
6pinia.use(piniaPluginPersistedstate)

Użycie w store:

1export const useSettingsStore = defineStore('settings', () => {
2  const theme = ref('dark')
3  const language = ref('pl')
4
5  return { theme, language }
6}, {
7  persist: true // Cały state do localStorage
8})

Zaawansowana konfiguracja persist

1export const useAuthStore = defineStore('auth', () => {
2  const token = ref(null)
3  const user = ref(null)
4  const tempData = ref(null) // Nie chcemy tego zapisywać
5
6  return { token, user, tempData }
7}, {
8  persist: {
9    // Tylko wybrane pola
10    paths: ['token'],
11
12    // Custom storage
13    storage: sessionStorage,
14
15    // Custom key
16    key: 'nova-lab-auth'
17  }
18})

Tworzenie custom pluginu

Plugin Pinia to funkcja przyjmująca context ze store:

1// plugins/logger.js
2export function loggerPlugin({ store }) {
3  store.$subscribe((mutation, state) => {
4    console.log(`[${mutation.storeId}] ${mutation.type}`)
5  })
6
7  store.$onAction(({ name, store: s, args }) => {
8    console.log(`[${s.$id}] Action: ${name}`, args)
9  })
10}
11
12// main.js
13const pinia = createPinia()
14pinia.use(loggerPlugin)

Plugin dodający właściwości

1function timestampPlugin({ store }) {
2  // Dodaj lastUpdated do każdego store
3  store.lastUpdated = ref(null)
4
5  store.$subscribe(() => {
6    store.lastUpdated = new Date()
7  })
8}
Vai a CodeWorlds