Vuex数据持久化
在刷新页面时Vuex中的数据会重置
,对于想要保留的状态同样也会重置
在Storage中数据可以持久化存储,但是在存储了太多数据时不利于状态的统一管理
核心:commit时备份一份数据在本地
以登录验证token为例
1.Storage的简单封装
// @/utiles/storage.js
const Storage = class {
constructor(isLocal) {
this.isLocal = isLocal
}
has(key) {
if (this.isLocal) {
return Reflect.has(localStorage, key)
} else {
return Reflect.has(sessionStorage, key)
}
}
set(key, value) {
if (this.isLocal) {
localStorage.setItem(key, JSON.stringify(value))
} else {
sessionStorage.setItem(key, JSON.stringify(value))
}
}
get(key) {
if (this.has(key)) {
if (this.isLocal) {
return JSON.parse(localStorage.getItem(key))
} else {
return JSON.parse(sessionStorage.getItem(key))
}
}
return false
}
remove(key) {
if (this.has(key)) {
if (this.storageType) {
localStorage.removeItem(key)
} else {
sessionStorage.removeItem(key)
}
return true
}
return false
}
clear() {
if (this.isLocal) {
localStorage.clear()
} else {
sessionStorage.clear()
}
}
}
const local = new Storage(true)
const session = new Storage(false)
export { Storage, local, session }
2. Vuex
// @/store/modules/user.js
import {local,session} from '@/utils/storage.js'
import { request } from '@/api/request.js' //接口封装
const user = {
namespaced:true,
state:{
loginInfo:{
userId:'',
pwd:'',
},
token:'',
},
mutations:{
SET_LOGININFO: (state,loginInfo)=>{
state.loginInfo = loginInfo
local.set('loginInfo',loginInfo)
},
SET_TOKEN:(state,token) => {
state.token = token
session.set('token',token)
}
},
actions:{
async Login({commit,state},loginInfo){
// 请求token
let token =await request('login',loginInfo)
commit('SET_LOGININFO',loginInfo)
commit('SET_TOKEN',token)
},
Logout({commit}){
commit('SET_TOKEN','')
session.clear()
}
persistUser({commit}){
commit('SET_LOGININFO',local.get('loginInfo'))
commit('SET_TOKEN',session.get('token'))
}
}
}
export default user
// @/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user form './modules.js'
Vue.use(Vuex)
const store = new Vuex.Store({
modules:{
user
}
})
export default store
3. 路由守卫
// @/router/permission.js
import {router} from './index.js'
import store from '@/store/index.js'
router.beforEach((to,from,next)=> {
store.dispatch('user/persistUser')
if(store.state.user.token){
if(to.path === '/login'){
next({path:'/'})
}else{
next()
}
}else {
next(`/login?redirect=${to.fullPath}`)
}
})