解決vuex頁面刷新導致數據丟失問題
vuex數據是存在內存當中,當頁面刷新之后vuex數據自然會丟失。我們有兩種方法解決該問題:
1.使用vuex-along
2.使用localStorage或者sessionStroage
1.使用vuex-along
vuex-along的實質也是將vuex中的數據存放到localStorage或者sessionStroage中,只不過這個存取過程這個組件會幫我們完成,我們只需要用vuex的讀取數據方式操作就可以了,簡單了解一下vuex-along的使用方法。
安裝vuex-along:
1
|
npm install vuex-along --save |
配置vuex-along: 在store/index.js 中最后添加以下代碼:
1
|
import VueXAlong from 'vuex-along' //導入插件 |
1
2
3
4
5
6
7
8
9
10
|
export default new Vuex.Store({ //modules: { //controler //模塊化vuex //}, plugins: [VueXAlong({ name: 'store' , //存放在localStroage或者sessionStroage 中的名字 local: false , //是否存放在local中 false 不存放 如果存放按照下面session的配置 session: { list: [], isFilter: true } //如果值不為false 那么可以傳遞對象 其中 當isFilter設置為true時, list 數組中的值就會被過濾調,這些值不會存放在seesion或者local中 })] }); |
2.使用localStorage或者sessionStroage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
created() { //在頁面加載時讀取sessionStorage里的狀態信息 if (sessionStorage.getItem( "store" )) { this .$store.replaceState( Object.assign( {}, this .$store.state, JSON.parse(sessionStorage.getItem( "store" )) ) ); } //在頁面刷新時將vuex里的信息保存到sessionStorage里 window.addEventListener( "beforeunload" , () => { sessionStorage.setItem( "store" , JSON.stringify( this .$store.state)); }); }, |
上面兩種方法都可以解決vuex頁面刷新導致數據丟失問題。按照上面的方法配置之后就可以正常使用vuex了,頁面刷新數據也不會丟失了。
以上就是vuex頁面刷新導致數據丟失的解決方案的詳細內容,更多關于vuex 數據丟失的資料請關注服務器之家其它相關文章!
原文鏈接:https://segmentfault.com/a/1190000038400475