vuex-persistedstate
- 核心原理:在本地存儲中存入所有的vuex數據,頁面刷新時到緩存中取數據,放到vuex中
-
下載:
$ npm install vuex-persistedstate -S
- 在store中引入插件
1
2
3
4
5
|
import persistedState from 'vuex-persistedstate' const store = new Vuex.Store({ // ... plugins: [persistedState()] }) |
vuex-persistedstate
默認使用localStorage儲存,若想使用sessionStorage,可采用以下配置
1
2
3
4
5
6
7
|
import persistedState from "vuex-persistedstate" const store = new Vuex.Store({ // ... plugins: [persistedState ({ storage: window.sessionStorage })] }) |
- 若想使用cookie,可采用以下配置
-
下載:
$ npm install js-cookie -S
1
2
3
4
5
6
7
8
9
10
11
12
|
import Cookies from 'js-cookie' ; import persistedState from "vuex-persistedstate" const store = new Vuex.Store({ // ... plugins: [persistedState ({ storage: { getItem: key => Cookies.get(key), setItem: (key, value) => Cookies.set(key, value), removeItem: key => Cookies.remove(key) } })] }) |
secure-ls
- 加密storage
-
當我們在vuex中保存了用戶信息,雖然使用起來方便了很多,但是為了解決vuex刷新頁面數據丟失的問題,使用了
vuex-persistedstate
插件,vuex-persistedstate
是沒有加密的,用戶的信息就暴露在緩存中, -
非常的不安全,所以需要配合
secure-ls
來加密storage -
下載:
$ npm install secure-ls -S
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import Vue from "vue" ; import Vuex from "vuex" ; import SecureLS from 'secure-ls' ; import persistedState from "vuex-persistedstate" ; const ls = new SecureLS({ encodingType: "aes" , // 加密方式 isCompression: false , // 是否啟用數據壓縮 encryptionSecret: "old-beauty" // }); Vue.use(Vuex); export default new Vuex.Store({ ... plugins: [persistedState({ // key: "123123", // 存入storage是的key storage: { getItem: key => ls.get(key), setItem: (key, value) => ls.set(key, value), removeItem: key => ls.remove(key) } })], }); |
【注】vuex-persist(不兼容ie) vuex-persistedstate
到此這篇關于vuex強刷數據丟失的文章就介紹到這了,更多相關vuex數據丟失內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_43014319/article/details/115353329