pinia持久化插件pinia-plugin-persist的使用
# 安装
yarn add pinia-plugin-persist
1
# 设置
# vue2
import Vue from 'vue'
import vueCompositionApi from '@vue/composition-api'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
import App from './App.vue'
const pinia = createPinia()
pinia.use(piniaPersist)
Vue.use(vueCompositionApi)
Vue.use(pinia)
new Vue({
pinia,
render: h => h(App),
}).$mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# vue3
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPersist)
createApp({})
.use(pinia)
.mount('#app')
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# typescript定义
{
"compilerOptions": {
"types": [
"pinia-plugin-persist"
]
},
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 基本使用
在store
中启用持久化插件,默认情况下将整个状态存储在会话存储中。
// store/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('storeUser', {
state: () => {
return {
firstName: 'S',
lastName: 'L',
accessToken: 'xxxxxxxxxxxxx'
}
},
actions: {
setToken (value: string) {
this.accessToken = value
}
},
persist: {
enabled: true // 启用插件
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 自定义存储策略
可以定义多种存储策略保存数据
每个存储策略都是一个对象
interface PersistStrategy {
key?: string; // 存储的key名
storage?: Storage; // 保存方式 (默认: sessionStorage)
paths?: string[]; // 列出要存储在存储器中的状态键
}
1
2
3
4
5
2
3
4
5
import Cookies from 'js-cookie'
// 定制存储
const cookiesStorage: Storage = {
setItem (key, state) {
return Cookies.set('accessToken', state.accessToken, { expires: 3 })
},
getItem (key) {
return JSON.stringify({
accessToken: Cookies.getJSON('accessToken'),
})
},
}
export const useUserStore = defineStore('storeUser', {
state () {
return {
firstName: 'S',
lastName: 'L',
accessToken: 'xxxxxxxxxxxxx',
}
},
persist: {
enabled: true,
// 通过strategies定义多个存储策略
strategies: [
{key: 'user', storage: localStorage,}, // 将状态保存在localStorage键名为user下
{ storage: sessionStorage, paths: ['firstName', 'lastName'] }, // 保留部分状态到sessionStorage
{ storage: localStorage, paths: ['accessToken'] },// 保留部分状态到localStorage
{ storage: cookiesStorage, paths: ['accessToken'] }, // 定制存储
],
},
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
上次更新: 2023/09/22, 16:54:32