vuex實(shí)現(xiàn)數(shù)據(jù)持久化的兩種方案
方案一:
封裝 storage 存儲(chǔ)模塊,利用本地存儲(chǔ),進(jìn)行 vuex 持久化處理方案二:
安裝一個(gè)vuex的插件 vuex-persistedstate 來(lái)支持vuex的狀態(tài)持久化
方案一
在封裝儲(chǔ)存模塊之前,我們有必要先復(fù)習(xí)一下localStorage和JSON.stringify() 的知識(shí)
localStorage
介紹
只讀的 localStorage 屬性允許你訪問(wèn)一個(gè)Document 源(origin)的對(duì)象 Storage;存儲(chǔ)的數(shù)據(jù)將保存在瀏覽器會(huì)話中。 localStorage類(lèi)似 sessionStorage,但其區(qū)別在于:存儲(chǔ)在 localStorage 的數(shù)據(jù)可以長(zhǎng)期保留;而當(dāng)頁(yè)面會(huì)話結(jié)束——也就是說(shuō),當(dāng)頁(yè)面被關(guān)閉時(shí),存儲(chǔ)在 sessionStorage 的數(shù)據(jù)會(huì)被清除。
應(yīng)注意,無(wú)論數(shù)據(jù)存儲(chǔ)在 localStorage 還是 sessionStorage ,它們都特定于頁(yè)面的協(xié)議。
另外, localStorage 中的鍵值對(duì)總是以字符串的形式存儲(chǔ)。 (需要注意,和 js 對(duì)象相比,鍵值對(duì)總是以字符串的形式存儲(chǔ)意味著數(shù)值類(lèi)型會(huì)自動(dòng)轉(zhuǎn)化為字符串類(lèi)型).
值
一個(gè)可被用于訪問(wèn)當(dāng)前源(origin)的本地存儲(chǔ)空間的 Storage 對(duì)象。
示例
下面的代碼片段訪問(wèn)了當(dāng)前域名下的本地 Storage 對(duì)象,并通過(guò) Storage.setItem() 增加了一個(gè)數(shù)據(jù)項(xiàng)目。
localStorage.setItem("myCat", "Tom");該語(yǔ)法用于讀取 localStorage 項(xiàng),如下:
let cat = localStorage.getItem("myCat");該語(yǔ)法用于移除 localStorage 項(xiàng),如下:
localStorage.removeItem("myCat");該語(yǔ)法用于移除所有的 localStorage 項(xiàng),如下:
// 移除所有 localStorage.clear();
JSON.stringify()
介紹
JSON.stringify()方法將一個(gè) JavaScript 對(duì)象或值轉(zhuǎn)換為 JSON 字符串,如果指定了一個(gè) 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"'語(yǔ)法
JSON.stringify(value[, replacer [, space]])
參數(shù)
value
將要序列化成 一個(gè) JSON 字符串的值。
replacer (可選)
如果該參數(shù)是一個(gè)函數(shù),則在序列化過(guò)程中,被序列化的值的每個(gè)屬性都會(huì)經(jīng)過(guò)該函數(shù)的轉(zhuǎn)換和處理;如果該參數(shù)是一個(gè)數(shù)組,則只有包含在這個(gè)數(shù)組中的屬性名才會(huì)被序列化到最終的 JSON 字符串中;如果該參數(shù)為 null 或者未提供,則對(duì)象所有的屬性都會(huì)被序列化。
space(可選)
指定縮進(jìn)用的空白字符串,用于美化輸出(pretty-print);如果參數(shù)是個(gè)數(shù)字,它代表有多少的空格;上限為 10。該值若小于 1,則意味著沒(méi)有空格;如果該參數(shù)為字符串(當(dāng)字符串長(zhǎng)度超過(guò) 10 個(gè)字母,取其前 10 個(gè)字母),該字符串將被作為空格;如果該參數(shù)沒(méi)有提供(或者為 null),將沒(méi)有空格。
返回值
一個(gè)表示給定值的 JSON 字符串
使用JSON.stringify() 結(jié)合localStorage的例子
一些時(shí)候,你想存儲(chǔ)用戶創(chuàng)建的一個(gè)對(duì)象,并且,即使在瀏覽器被關(guān)閉后仍能恢復(fù)該對(duì)象。下面的例子是 JSON.stringify 適用于這種情形的一個(gè)樣板:
// 創(chuàng)建一個(gè)示例數(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 轉(zhuǎn)換為 JSON 字符串
// 然后使用 localStorage 保存在 session 名稱(chēng)里
localStorage.setItem("session", JSON.stringify(session));
// 然后是如何轉(zhuǎn)換通過(guò) JSON.stringify 生成的字符串,該字符串以 JSON 格式保存在 localStorage 里
var restoredSession = JSON.parse(localStorage.getItem("session"));
// 現(xiàn)在 restoredSession 包含了保存在 localStorage 里的對(duì)象
console.log(restoredSession);具體步驟
1.封裝storage 存儲(chǔ)模塊
// 約定一個(gè)通用的鍵名
const INFO_KEY = 'hm_shopping_info'
// 獲取個(gè)人信息
export const getInfo = () => {
const defaultObj = { token: '', userId: '' }
const result = localStorage.getItem(INFO_KEY)
return result ? JSON.parse(result) : defaultObj
}
// 設(shè)置個(gè)人信息
export const setInfo = (obj) => {
localStorage.setItem(INFO_KEY, JSON.stringify(obj))
}
// 移除個(gè)人信息
export const removeInfo = () => {
localStorage.removeItem(INFO_KEY)
}2.創(chuàng)建user.jx文件,將數(shù)據(jù)存入vuex的同時(shí)也存入本地
import { getInfo, setInfo } from '@/utils/storage'
export default {
namespaced: true,
state () {
return {
// 個(gè)人權(quán)證相關(guān)
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({
// 存儲(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):
- storage為存儲(chǔ)方式,可選值為localStorage、sessionStorage和cookies;
- localStorage和sessionStorage兩種存儲(chǔ)方式可以采用上述代碼中的寫(xiě)法,若想采用cookies坐位數(shù)據(jù)存儲(chǔ)方式,則需要另外一種寫(xiě)法;
- render接收一個(gè)函數(shù),返回值為一個(gè)對(duì)象;返回的對(duì)象中的鍵值對(duì)既是要持久化存儲(chǔ)的數(shù)據(jù);
- 若想持久化存儲(chǔ)部分?jǐn)?shù)據(jù),請(qǐng)?jiān)?strong>return的對(duì)象中采用key:value鍵值對(duì)的方式進(jìn)行數(shù)據(jù)存儲(chǔ),render函數(shù)中的參數(shù)既為state對(duì)象。
以上就是vuex實(shí)現(xiàn)數(shù)據(jù)持久化的兩種方案的詳細(xì)內(nèi)容,更多關(guān)于vuex數(shù)據(jù)持久化的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue打包部署到springboot的實(shí)現(xiàn)示例
項(xiàng)目開(kāi)發(fā)中,一般我們都會(huì)使用SpringBoot+Vue進(jìn)行前后端開(kāi)發(fā),本文主要介紹了vue打包部署到springboot的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-07-07
vue 組件的封裝之基于axios的ajax請(qǐng)求方法
今天小編就為大家分享一篇vue 組件的封裝之基于axios的ajax請(qǐng)求方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
vue中keep-alive組件使用和一些基礎(chǔ)配置方法
本文主要介紹了Vue中keep-alive組件的使用方法和一些基礎(chǔ)配置,keep-alive是Vue中的一個(gè)抽象組件,可以緩存組件實(shí)例,提高性能,本文給大家介紹vue中keep-alive組件使用和一些基礎(chǔ)配置方法,感興趣的朋友一起看看吧2024-10-10
vue3實(shí)現(xiàn)ai聊天對(duì)話框功能
這篇文章主要介紹了vue3實(shí)現(xiàn)ai聊天對(duì)話框功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-12-12
vue3輸入框生成的時(shí)候如何自動(dòng)獲取焦點(diǎn)詳解
記錄一下自己最近開(kāi)發(fā)vue3.0的小小問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于vue3輸入框生成的時(shí)候如何自動(dòng)獲取焦點(diǎn)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
Vue.extend 登錄注冊(cè)模態(tài)框的實(shí)現(xiàn)
這篇文章主要介紹了Vue.extend 登錄注冊(cè)模態(tài)框的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
vue中使用cookies和crypto-js實(shí)現(xiàn)記住密碼和加密的方法
這篇文章給大家介紹一下關(guān)于vue中使用cookies和crypto-js如何實(shí)現(xiàn)密碼的加密與記住密碼,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你們有所幫助。2018-10-10

