1. When to use pinia-plugin-persistedstate?
Both pinia and vuex are state management tools. There is no doubt that whether it is pinia or vuex, data persistence can be achieved through the localStorage.setItem() method (of course there are other methods of data persistence, which will not be listed here. ), but if you need to save the data in the entire store, you only need to use pinia-plugin-persistedstate for simple configuration to get everything done
2. Specific steps
(1) Install the plugin:
pnpm, npm, yarn can choose one of the commonly used downloading methods
pnpm i pinia-plugin-persistentstate
npm i pinia-plugin-persistedstate
yarn add pinia-plugin-persistedstate
(2) Hang the plugin on the pinia instance
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'const pinia = createPinia()
pinia.use(piniaPluginPersistedstate )
(3) Configure in store: set persist
to true
1. Combined API writing method:
{ persist: true }
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/types/user'
export const useStoreUser = defineStore(
'use',
() => {
const user = ref<User>()
return { user }
},
{
persist: true
}
)
You can view the saved data in localStorage
2. Optional API writing method:
persist: true
import { defineStore } from 'pinia'
export const useStoreUser = defineStore('use', {
state: () => {
return {
user: '用户信息'
}
},
persist: true
})
3. Related configuration
1. The pinia-plugin-persistedstate plugin is stored in localStorage by default. If it needs to be stored in sessionStorage, the following configuration needs to be added:
export const useStoreUser = defineStore('use', {
state: () => {
return {
user: '用户信息'
}
},
persist: {
storage: sessionStorage
}
})
2. The default stored key is the name of the store, but the key can also be customized:
export const useStoreUser = defineStore('use', {
state: () => {
return {
user: '用户信息'
}
},
persist: {
key: 'userInfo'
}
})
3. The value stored by default is all the data defined in the store. If only part of the data needs to be stored, just add the variable name to be stored to the paths array:
paths: [] indicates that the data of the entire state is not persisted
paths: undefined or null indicates that the data of the entire state is persisted
The following example stores only token and user, but not id:
export const useStoreUser = defineStore('use', {
state: () => {
return {
user: '用户信息',
id:1111111,
token:123456789
}
},
persist: {
paths:['token','user']
}
})
Official documentation of pinia-plugin-persistedstate:
Quick start | pinia-plugin-persistedstate (prazdevs.github.io)