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