vuex實現(xiàn)數(shù)據(jù)持久化的兩種方案
方案一:
封裝 storage 存儲模塊,利用本地存儲,進行 vuex 持久化處理方案二:
安裝一個vuex的插件 vuex-persistedstate 來支持vuex的狀態(tài)持久化
方案一
在封裝儲存模塊之前,我們有必要先復習一下localStorage和JSON.stringify() 的知識
localStorage
介紹
只讀的 localStorage 屬性允許你訪問一個Document 源(origin)的對象 Storage;存儲的數(shù)據(jù)將保存在瀏覽器會話中。 localStorage類似 sessionStorage,但其區(qū)別在于:存儲在 localStorage 的數(shù)據(jù)可以長期保留;而當頁面會話結束——也就是說,當頁面被關閉時,存儲在 sessionStorage 的數(shù)據(jù)會被清除。
應注意,無論數(shù)據(jù)存儲在 localStorage 還是 sessionStorage ,它們都特定于頁面的協(xié)議。
另外, localStorage 中的鍵值對總是以字符串的形式存儲。 (需要注意,和 js 對象相比,鍵值對總是以字符串的形式存儲意味著數(shù)值類型會自動轉化為字符串類型).
值
一個可被用于訪問當前源(origin)的本地存儲空間的 Storage 對象。
示例
下面的代碼片段訪問了當前域名下的本地 Storage 對象,并通過 Storage.setItem() 增加了一個數(shù)據(jù)項目。
localStorage.setItem("myCat", "Tom");該語法用于讀取 localStorage 項,如下:
let cat = localStorage.getItem("myCat");該語法用于移除 localStorage 項,如下:
localStorage.removeItem("myCat");該語法用于移除所有的 localStorage 項,如下:
// 移除所有 localStorage.clear();
JSON.stringify()
介紹
JSON.stringify()方法將一個 JavaScript 對象或值轉換為 JSON 字符串,如果指定了一個 replacer 函數(shù),則可以選擇性地替換值,或者指定的 replacer 是數(shù)組,則可選擇性地僅包含數(shù)組指定的屬性。
console.log(JSON.stringify({ x: 5, y: 6 }));
// Expected output: '{"x":5,"y":6}'
console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// Expected output: '[3,"false",false]'
console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol('')] }));
// Expected output: '{"x":[10,null,null,null]}'
console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// Expected output: '"2006-01-02T15:04:05.000Z"'語法
JSON.stringify(value[, replacer [, space]])
參數(shù)
value
將要序列化成 一個 JSON 字符串的值。
replacer (可選)
如果該參數(shù)是一個函數(shù),則在序列化過程中,被序列化的值的每個屬性都會經(jīng)過該函數(shù)的轉換和處理;如果該參數(shù)是一個數(shù)組,則只有包含在這個數(shù)組中的屬性名才會被序列化到最終的 JSON 字符串中;如果該參數(shù)為 null 或者未提供,則對象所有的屬性都會被序列化。
space(可選)
指定縮進用的空白字符串,用于美化輸出(pretty-print);如果參數(shù)是個數(shù)字,它代表有多少的空格;上限為 10。該值若小于 1,則意味著沒有空格;如果該參數(shù)為字符串(當字符串長度超過 10 個字母,取其前 10 個字母),該字符串將被作為空格;如果該參數(shù)沒有提供(或者為 null),將沒有空格。
返回值
一個表示給定值的 JSON 字符串
使用JSON.stringify() 結合localStorage的例子
一些時候,你想存儲用戶創(chuàng)建的一個對象,并且,即使在瀏覽器被關閉后仍能恢復該對象。下面的例子是 JSON.stringify 適用于這種情形的一個樣板:
// 創(chuàng)建一個示例數(shù)據(jù)
var session = {
screens: [],
state: true,
};
session.screens.push({ name: "screenA", width: 450, height: 250 });
session.screens.push({ name: "screenB", width: 650, height: 350 });
session.screens.push({ name: "screenC", width: 750, height: 120 });
session.screens.push({ name: "screenD", width: 250, height: 60 });
session.screens.push({ name: "screenE", width: 390, height: 120 });
session.screens.push({ name: "screenF", width: 1240, height: 650 });
// 使用 JSON.stringify 轉換為 JSON 字符串
// 然后使用 localStorage 保存在 session 名稱里
localStorage.setItem("session", JSON.stringify(session));
// 然后是如何轉換通過 JSON.stringify 生成的字符串,該字符串以 JSON 格式保存在 localStorage 里
var restoredSession = JSON.parse(localStorage.getItem("session"));
// 現(xiàn)在 restoredSession 包含了保存在 localStorage 里的對象
console.log(restoredSession);具體步驟
1.封裝storage 存儲模塊
// 約定一個通用的鍵名
const INFO_KEY = 'hm_shopping_info'
// 獲取個人信息
export const getInfo = () => {
const defaultObj = { token: '', userId: '' }
const result = localStorage.getItem(INFO_KEY)
return result ? JSON.parse(result) : defaultObj
}
// 設置個人信息
export const setInfo = (obj) => {
localStorage.setItem(INFO_KEY, JSON.stringify(obj))
}
// 移除個人信息
export const removeInfo = () => {
localStorage.removeItem(INFO_KEY)
}2.創(chuàng)建user.jx文件,將數(shù)據(jù)存入vuex的同時也存入本地
import { getInfo, setInfo } from '@/utils/storage'
export default {
namespaced: true,
state () {
return {
// 個人權證相關
userInfo: getInfo()
}
},
mutations: {
setUserInfo (state, obj) {
state.userInfo = obj
setInfo(obj)
}
},
actions: {},
getters: {}
}方案二
安裝插件
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({
// 存儲方式:localStorage、sessionStorage、cookies
storage: window.sessionStorage,
// 存儲的 key 的key值
key: "store",
render(state) {
// 要存儲的數(shù)據(jù):本項目采用es6擴展運算符的方式存儲了state中所有的數(shù)據(jù)
return { ...state };
}
})
]
});
export default store;vuex中module數(shù)據(jù)的持久化存儲
/* 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]
});
注意事項:
- storage為存儲方式,可選值為localStorage、sessionStorage和cookies;
- localStorage和sessionStorage兩種存儲方式可以采用上述代碼中的寫法,若想采用cookies坐位數(shù)據(jù)存儲方式,則需要另外一種寫法;
- render接收一個函數(shù),返回值為一個對象;返回的對象中的鍵值對既是要持久化存儲的數(shù)據(jù);
- 若想持久化存儲部分數(shù)據(jù),請在return的對象中采用key:value鍵值對的方式進行數(shù)據(jù)存儲,render函數(shù)中的參數(shù)既為state對象。
以上就是vuex實現(xiàn)數(shù)據(jù)持久化的兩種方案的詳細內(nèi)容,更多關于vuex數(shù)據(jù)持久化的資料請關注腳本之家其它相關文章!
相關文章
Vue Element UI 表單自定義校驗規(guī)則及使用
這篇文章主要介紹了Vue Element UI 表單自定義效驗規(guī)則及使用,文中通過代碼介紹了常見表單效驗規(guī)則,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
vue如何實現(xiàn)跨頁面?zhèn)鬟f與接收數(shù)組并賦值
這篇文章主要介紹了vue如何實現(xiàn)跨頁面?zhèn)鬟f與接收數(shù)組并賦值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
vue.config.js配置proxy代理產(chǎn)生404錯誤的原因及解決
這篇文章主要介紹了vue.config.js配置proxy代理產(chǎn)生404錯誤的原因及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
ElementUI中el-input無法輸入、修改及刪除問題解決辦法
這篇文章主要給大家介紹了關于ElementUI中el-input無法輸入、修改及刪除問題的解決辦法,這種問題產(chǎn)生是因為input在vue中的受控,我們需要去重新改變一下監(jiān)聽和實現(xiàn),需要的朋友可以參考下2023-11-11
vue在mounted拿不到props中傳遞的數(shù)據(jù)問題
這篇文章主要介紹了vue在mounted拿不到props中傳遞的數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

