溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vuex數(shù)據(jù)持久化的實(shí)現(xiàn)方法有哪些

發(fā)布時(shí)間:2021-07-13 14:52:21 來源:億速云 閱讀:613 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“vuex數(shù)據(jù)持久化的實(shí)現(xiàn)方法有哪些”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

目錄
  • 業(yè)務(wù)需求:

  • 方案一:vuex-persistedstate

  • 方案二:vuex-persist

  • 總結(jié)

業(yè)務(wù)需求:

在基于vue開發(fā)SPA項(xiàng)目時(shí),為了解決頁面刷新后數(shù)據(jù)丟失的問題,我們一般都是將數(shù)據(jù)存儲(chǔ)在localstorage或sessionstorage中;當(dāng)數(shù)據(jù)需要全局處理統(tǒng)一管理時(shí),我們也會(huì)借助于vue官方提供的vuex來進(jìn)行數(shù)據(jù)的統(tǒng)一管理。vuex相比localstorage或sessionstorage來說,存儲(chǔ)數(shù)據(jù)更安全些。與此同時(shí),vuex也存在一些弊端,當(dāng)頁面刷新后,vuex中state存儲(chǔ)的數(shù)據(jù)同時(shí)也會(huì)被更新,vuex中存儲(chǔ)的數(shù)據(jù)不能持久化,需要監(jiān)聽處理來維持vuex存儲(chǔ)的數(shù)據(jù)狀態(tài)持久化。

為解決頁面刷新后vuex中存儲(chǔ)的數(shù)據(jù)狀態(tài)不能持久化的問題,我采取的方案是借助第三方插件工具來實(shí)現(xiàn)vuex數(shù)據(jù)的持久化存儲(chǔ),來解決頁面刷新后數(shù)據(jù)更新的問題。

方案一:vuex-persistedstate

安裝插件

yarn add vuex-persistedstate
// 或
npm install --save vuex-persistedstate

使用方法

import Vuex from "vuex";
// 引入插件
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

const state = {};
const mutations = {};
const actions = {};

const store = new Vuex.Store({
	state,
	mutations,
	actions,
  /* vuex數(shù)據(jù)持久化配置 */
	plugins: [
		createPersistedState({
      // 存儲(chǔ)方式:localStorage、sessionStorage、cookies
			storage: window.sessionStorage,
      // 存儲(chǔ)的 key 的key值
			key: "store",
			render(state) {
        // 要存儲(chǔ)的數(shù)據(jù):本項(xiàng)目采用es6擴(kuò)展運(yùn)算符的方式存儲(chǔ)了state中所有的數(shù)據(jù)
				return { ...state };
			}
		})
	]
});

export default store;

vuex中module數(shù)據(jù)的持久化存儲(chǔ)

/* module.js */
export const dataStore = {
  state: {
    data: []
  }
}
 
/* store.js */
import { dataStore } from './module'
 
const dataState = createPersistedState({
  paths: ['data']
});
 
export new Vuex.Store({
  modules: {
    dataStore
  },
  plugins: [dataState]
});

注意事項(xiàng):

  1. storage為存儲(chǔ)方式,可選值為localStorage、sessionStorage和cookies;

  2. localStorage和sessionStorage兩種存儲(chǔ)方式可以采用上述代碼中的寫法,若想采用cookies坐位數(shù)據(jù)存儲(chǔ)方式,則需要另外一種寫法;

  3. render接收一個(gè)函數(shù),返回值為一個(gè)對(duì)象;返回的對(duì)象中的鍵值對(duì)既是要持久化存儲(chǔ)的數(shù)據(jù);

  4. 若想持久化存儲(chǔ)部分?jǐn)?shù)據(jù),請(qǐng)?jiān)趓eturn的對(duì)象中采用key:value鍵值對(duì)的方式進(jìn)行數(shù)據(jù)存儲(chǔ),render函數(shù)中的參數(shù)既為state對(duì)象。

方案二:vuex-persist

安裝插件

yarn add vuex-persist
// 或
npm install --save vuex-persist

使用方法

import Vuex from "vuex";
// 引入插件
import VuexPersistence from "vuex-persist";

Vue.use(Vuex);
//  初始化
const state = {
	userName:'admin'
};
const mutations = {};
const actions = {};
// 創(chuàng)建實(shí)例
const vuexPersisted = new VuexPersistence({
	storage: window.sessionStorage,
  render:state=>({
  	userName:state.userName
    // 或
    ...state
  })
});

const store = new Vuex.Store({
	state,
  actions,
  mutations,
  // 數(shù)據(jù)持久化設(shè)置
  plugins:[vuexPersisted.plugins]
});

export default store;

屬性方法

屬性值數(shù)據(jù)類型描述
keystringThe key to store the state in the storage_Default: 'vuex'_
storageStorage (Web API)localStorage, sessionStorage, localforage or your custom Storage object.Must implement getItem, setItem, clear etc.Default: window.localStorage
saveStatefunction(key, state[, storage])If not using storage, this custom function handles saving state to persistence
reducerfunction(state) => objectState reducer. reduces state to only those values you want to save. By default, saves entire state
filterfunction(mutation) => booleanMutation filter. Look at mutation.type and return true for only those ones which you want a persistence write to be triggered for. Default returns true for all mutations
modulesstring[]List of modules you want to persist. (Do not write your own reducer if you want to use this)
asyncStoragebooleanDenotes if the store uses Promises (like localforage) or not (you must set this to true when suing something like localforage)Default: false
supportCircularbooleanDenotes if the state has any circular references to it self(state.x === state)Default: false

總結(jié)

上述兩種方案都可以實(shí)現(xiàn)vuex數(shù)據(jù)持久化存儲(chǔ)。方案一是我在實(shí)際開發(fā)過程中用到的,方案二是在Github上看到的,綜合來說,兩者都可以時(shí)間最終的需求,而且都有對(duì)應(yīng)的案例Demo可以參考。相比來說方案一在GitHub上的start數(shù)要高于方案二。

請(qǐng)結(jié)合實(shí)際情況選擇符合自己的方案!

“vuex數(shù)據(jù)持久化的實(shí)現(xiàn)方法有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI