詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題
眾所周知,vuex的一個全局狀態(tài)管理的插件,但是在瀏覽器刷新的時候,內(nèi)存中的state會釋放,通常的解決辦法就是用本地存儲的方式保存數(shù)據(jù),然后再vuex初始化的時候再賦值給state,手動存再手動取會覺得很麻煩,這個時候就可以使用vuex的插件vuex-solidification
插件地址: vuex-solidification , 歡迎star
插件原理
vuex有一個hook方法:store.subscribe((mutation, state) => {}) 每次在mutation方法執(zhí)行完之后都會調(diào)用這個回調(diào)函數(shù),返回執(zhí)行完畢之后的state
使用方法
安裝
npm install --save vuex-solidification
引入及配置
import Vue from 'vue'
import Vuex from 'vuex'
import count from './count/index.js';
import createPersistedState from 'vuex-solidification';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: {
value: 0,
num: 1
},
pos: 1
}
plugins: [ // 默認存儲所有state數(shù)據(jù)到localstorage
createPersistedState()
]
});
插件參數(shù)說明
createPersistedState({options}) : Function
options里面可以有:
key: String 存儲到localStorage, sessionStorage 中對象的key,默認為vuex
local: Object 和 session: Object, 分別代表localStorage的配置和sessionStorage的配置
local 和 session 里面可以有: include: Array 和 exclude: Array
配置例子
createPersistedState({
local: {
include: ['count.value']
}
})
/*
hook鉤子觸發(fā)之后,localstorage里面存儲的對象為:
{
count: {
value: 0,
}
}
*/
createPersistedState({
local: {
exclude: ['count.value']
}
})
/*
hook鉤子觸發(fā)之后,localstorage里面存儲的對象為:
{
count: {
num: 1
},
pos: 1
}
*/
createPersistedState({
session: {
include: ['count.value']
}
})
/*
hook鉤子觸發(fā)之后,sessionstorage里面存儲的對象為:
{
count: {
value: 0,
}
}
*/
createPersistedState({
session: {
exclude: ['count.value']
}
})
/*
hook鉤子觸發(fā)之后,sessionstorage里面存儲的對象為:
{
count: {
num: 1
},
pos: 1
}
*/
createPersistedState({
session: {
include: ['count']
},
local: {
include: ['pos']
}
})
/*
hook鉤子觸發(fā)之后,
sessionstorage里面存儲的對象為:
{
count: {
value: 0,
num: 1
},
}
sessionstorage里面存儲的對象為:
{
pos: 0
}
*/
代碼例子
Check out the example on CodeSandbox.
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue限制輸入框只能輸入8位整數(shù)和2位小數(shù)的代碼
這篇文章主要介紹了vue限制輸入框只能輸入8位整數(shù)和2位小數(shù),文中我們使用v-model加watch 實現(xiàn)這一個功能,代碼簡單易懂,需要的朋友可以參考下2019-11-11
Vue TypeScript使用eval函數(shù)遇到的問題
近幾年前端對 TypeScript的呼聲越來越高,Typescript也成為了前端必備的技能。TypeScript是JS類型的超集,并支持了泛型、類型、命名空間、枚舉等特性,彌補了 JS 在大型應用開發(fā)中的不足2023-01-01
Vue.js每天必學之計算屬性computed與$watch
Vue.js每天必學之計算屬性computed與$watch,為大家詳細講解計算屬性computed與$watch,感興趣的小伙伴們可以參考一下2016-09-09
vue+ElementUI 關(guān)閉對話框清空驗證,清除form表單的操作
這篇文章主要介紹了vue+ElementUI 關(guān)閉對話框清空驗證,清除form表單的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue3.0 Reactive數(shù)據(jù)更新頁面沒有刷新的問題
這篇文章主要介紹了vue3.0 Reactive數(shù)據(jù)更新頁面沒有刷新的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

