共计 2140 个字符,预计需要花费 6 分钟才能阅读完成。
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}`)
}
})
在 actions 或组件中 commit 将
申请
或者要批改
的数据保留至 state 以及本地
刷新页面时在前置路由守卫
或者组件挂载
时 dispatch 将本地
的备份数据保留至 state
正文完