Initialize Pinia

import { createPinia } from 'pinia'

const pinia = createPinia()
pinia.use(SomePiniaPlugin) // Install the plugin for Pinia

const app = createApp(App)
app.use(pinia)
UseXxxStore () can only be called after app.use(pinia)
Copy the code

The use of the Store

  1. DefineStore accepts an ID, which must be different for different data sources
  2. The return value of useCounter() cannot be deconstructed, which would result in reactive loss of data
// src/stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counterStore', {
  state: () = > {
    return {j: 0.k: 0}}})// counter.js
import { useCounterStore } from 'path/to/src/stores/counterStore'

export default {
  setup() {
    const counterStore = useCounterStore()
    // Use counterstore. j and counterstore.k in the view
    // But you can't deconstruct the counterStore, you can only deconstruct it like this:
    const { j, k } = storeToRefs(counterStore)	
    return {
      counterStore, j, k,
    }
  },
}
Copy the code

Store Getters

Getters are simply a collection of store computed properties, and getters cannot be asynchronous functions

export const useStore = defineStore('main', {
  state: () = > ({
    counter: 0,}).getters: {
    doubleCount(state) {
      return state.counter * 2
    },
    doublePlusOne(): number {
      return this.doubleCount + 1 // getter To access another getter with this
    },
    getUserById: (state) = > { // A getter can return a function, but this invalidates the cache
      return (userId) = > state.users.find((user) = > user.id === userId)
    },
		otherGetter(state) { // You can also call other stores
      const otherStore = useOtherStore()
      return state.localData + otherStore.data
    },
  },
})
// Store. DoubleCount and store. DoublePlusOne can be used as properties directly
// store.getUserById(userId) can be used as a function
Copy the code

Store Actions

Actions are store methods and can be asynchronous functions

export const useUserStore = defineStore('users', {
  state: () = > ({
    userData: null,}).actions: {
    async signUp(email, password) {
      this.userData = await api.post({ email, password }).catch(error= > {
        showError(error); throwerror; })},}})// You can use userStore.signup (email, password)
Copy the code

store.$patch(object | fn)

counterStore.$patch(
   {j: counterStore.j + 1.name: 'j + 1'} 
)

cartStore.$patch((state) = > {
  state.items.push({ name: 'shoes'.quantity: 1 })
  state.hasChanged = true
})
Copy the code

store.$subscribe(fn)

Used to listen for overall changes in state.

cartStore.$subscribe((mutation, state) = > {
  // import { MutationType } from 'pinia'
  mutation.type // 'direct' | 'patch object' | 'patch function'
  mutation.storeId  
  mutation.payload // Get the parameters received by $patch

  localStorage.setItem('cart'.JSON.stringify(state))
})
Copy the code

Detached: true {detached: true} : {subscribe: true} : {subscribe: true} : {subscribe: true}

You can use Watch to achieve a similar effect:

watch(
  pinia.state,
  (state) = > {
    localStorage.setItem('piniaState'.JSON.stringify(state))
  },
  { deep: true})Copy the code

store.$onAction()

Monitor the execution of all actions.

const unsubscribe = someStore.$onAction(
  ({
    name, //The name of the action store,// store === someStore
    args, //Action's actual argument after,//After onError is executed after the action succeeds,//Execute onError} after action fails) = > {
    const startTime = Date.now()
    console.log('Start execution."${name}"Parameter is [${args.join(', ')}]. `)
    after((result) = > {
      console.log(
        'Executed successfully'${name}"WhenThe ${Date.now() - startTime}Ms \n Results in:${result}`
      )
    })
    onError((error) = > {
      console.warn(
        'Execution failed'${name}"WhenThe ${Date.now() - startTime}Ms \n reported an error as:${error}. `)})})// $onAction is automatically destroyed when the component it belongs to is uninstalled
// If you set the second argument of $onAction to true, then you need to call unsubscribe yourself to unsubscribe.
Copy the code

store.$reset()

You can reset state using counterStore.$reset()

store.$state

// The following two lines of code can override the original state
store.$state = { counter: Awesome!.name: 'Paimon' }
pinia.state.value = {} // This phrase is commonly used in SSR
Copy the code