国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

解決vue頁面刷新,數(shù)據(jù)丟失的問題

瀏覽:103日期:2022-10-24 10:46:03

在做vue項(xiàng)目的過程中有時(shí)候會遇到一個問題,就是進(jìn)行F5頁面刷新的時(shí)候,頁面的數(shù)據(jù)會丟失,出現(xiàn)這個問題的原因是因?yàn)楫?dāng)用vuex做全局狀態(tài)管理的時(shí)候,store中的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中的,頁面刷新時(shí)會重新加載vue實(shí)例,store中的數(shù)據(jù)就會被重新賦值,因此數(shù)據(jù)就丟失了,解決方式如下:

解決方法一:

最先想到的應(yīng)該就是利用localStorage/sessionStorage將數(shù)據(jù)儲存在外部,做一個持久化儲存,下面是利用localStorage存儲的具體方案:

方案一:由于state中的數(shù)據(jù)是響應(yīng)式的,而數(shù)據(jù)又是通過mutation來進(jìn)行修改,故在通過mutation修改state中數(shù)據(jù)的同時(shí)調(diào)用localStorage.setItem()方法來進(jìn)行數(shù)據(jù)的存儲。

import Vue from ’vue’;import Vuex from ’vuex’;Vue.use(Vuex);export default new Vuex.Store({ state: { orderList: [], menuList: [] }, mutations: { orderList(s, d) { s.orderList= d; window.localStorage.setItem('list',JSON.stringify(s.orderList)) }, menuList(s, d) { s.menuList = d; window.localStorage.setItem('list',JSON.stringify(s.menuList)) }, }})

在頁面加載的時(shí)候再通過localStorage.getItem()將數(shù)據(jù)取出放回到vuex,可在app.vue的created()周期函數(shù)中寫如下代碼:

if (window.localStorage.getItem('list') ) { this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem('list'))))}

方案二:方案一能夠順利解決問題,但不斷觸發(fā)localStorage.setItem()方法對性能不是特別友好,而且一直將數(shù)據(jù)同步到localStorage中似乎就沒必要再用vuex做狀態(tài)管理,直接用localStorage即可,于是對以上解決方法進(jìn)行了改進(jìn),通過監(jiān)聽beforeunload事件來進(jìn)行數(shù)據(jù)的localStorage存儲,beforeunload事件在頁面刷新時(shí)進(jìn)行觸發(fā),具體做法是在App.vue的created()周期函數(shù)中下如下代碼:

if (window.localStorage.getItem('list') ) { this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem('list')))) } window.addEventListener('beforeunload',()=>{ window.localStorage.setItem('list',JSON.stringify(this.$store.state)) })

解決方法二(推薦):

這個方法是基于對computed計(jì)算屬性的理解,在vue的官方文檔中有這么一段話:

解決vue頁面刷新,數(shù)據(jù)丟失的問題

由此得知計(jì)算屬性的結(jié)果會被緩存,也就是說在有緩存的情況下,computed會優(yōu)先使用緩存,于是也可以在state數(shù)據(jù)相對應(yīng)的頁面這樣寫:

computed:{ orderList() { return this.$store.state.orderList }}

以上就是解決vue頁面刷新,數(shù)據(jù)丟失的問題的詳細(xì)內(nèi)容,更多關(guān)于vue頁面刷新,數(shù)據(jù)丟失的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Vue
主站蜘蛛池模板: 三门县| 大丰市| 木兰县| 望江县| 永济市| 旌德县| 中牟县| 平定县| 长岭县| 舟山市| 玉溪市| 岳西县| 马龙县| 锡林浩特市| 福海县| 玉林市| 呼和浩特市| 苍南县| 井研县| 博兴县| 安阳市| 来宾市| 互助| 新乐市| 左贡县| 乐平市| 马公市| 嘉鱼县| 黄龙县| 凉城县| 景东| 根河市| 丹棱县| 滁州市| 永济市| 准格尔旗| 静安区| 长丰县| 勃利县| 滦南县| 贵州省|