欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vuex數(shù)據(jù)持久化的兩種方式:手動(dòng)存儲(chǔ)和vuex-persistedstate插件詳解

 更新時(shí)間:2024年08月31日 16:37:46   作者:一個(gè)好好的程序員  
這篇文章主要介紹了Vuex數(shù)據(jù)持久化的兩種方式:手動(dòng)存儲(chǔ)和vuex-persistedstate插件,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

第一部分:手動(dòng)存儲(chǔ)

vuex的 store 中的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中的,當(dāng)頁(yè)面刷新時(shí),頁(yè)面會(huì)重新加載 vue 實(shí)例,vuex里面的數(shù)據(jù)就會(huì)被重新賦值,這樣就會(huì)出現(xiàn)頁(yè)面刷新vuex中的數(shù)據(jù)丟失的問(wèn)題。

如何解決瀏覽器刷新數(shù)據(jù)丟失問(wèn)題呢?

方法一:全局監(jiān)聽

頁(yè)面刷新的時(shí)候?qū)?store 里 state 的值存到 sessionStorage 中,然后從sessionStorage 中獲取,再賦值給 store ,并移除 sessionStorage 中的數(shù)據(jù)。

在 app.vue 中添加以下代碼:

//在根組件.vue中添加如下代碼 app.vue
created () {
  window.addEventListener('beforeunload', () => {
    sessionStorage.setItem('list', JSON.stringify(this.$store.state))
   })
  try {
    sessionStorage.getItem('list') && this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('list'))))
   } catch (err) {
     console.log(err)
   }
   sessionStorage.removeItem('list')
  }

第二部分:利用vuex-persistedstate插件

vue2寫法

步驟:

第一步:運(yùn)行如下的命令,安裝持久化存儲(chǔ) vuex 中數(shù)據(jù)的第三方包:

npm i vuex-persistedstate

第二步:在 src/store/index.js 模塊中,導(dǎo)入并配置 vuex-persistedstate 包:

默認(rèn)存儲(chǔ)到localStorage

//vuex:store.js文件內(nèi)容如下
import Vue from 'vue'
import Vuex from 'vuex'
// 1. 導(dǎo)入包
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  // 2. 配置為 vuex 的插件
  plugins: [createPersistedState()],
  state: {
    token: ''
    ...
  },
})

想要存儲(chǔ)到sessionStorage,配置如下:

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState({
      storage: window.sessionStorage
  })]
})

vue3寫法

1)首先:我們需要安裝一個(gè)vuex的插件vuex-persistedstate來(lái)支持vuex的狀態(tài)持久化。

npm i vuex-persistedstate

2)然后:在src/store 文件夾下新建 modules 文件,在 modules 下新建 user.jscart.js

src/store/modules/user.js

3)繼續(xù):在 src/store/index.js 中導(dǎo)入 user cart 模塊。

import { createStore } from 'vuex'

import user from './modules/user'
import cart from './modules/cart'
import cart from './modules/category'

export default createStore({
  modules: {
    user,
    cart,
    category
  }
})

4)最后:使用vuex-persistedstate插件來(lái)進(jìn)行持久化

import { createStore } from 'vuex'
+import createPersistedstate from 'vuex-persistedstate'

import user from './modules/user'
import cart from './modules/cart'
import cart from './modules/category'

export default createStore({
  modules: {
    user,
    cart,
    category
  },
+  plugins: [
+    createPersistedstate({
+      key: 'erabbit-client-pc-store',
+      paths: ['user', 'cart'] //需要持久化的modules
+    })
+  ]
})

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論