在实际的vue项目中,当我们的应用遇到多个组件之间的共享问题时,通常会用到Vuex(一个状态管理的插件,可以解决不同组件之间的数据共享和数据持久化),解决组件之间同一状态的共享问题。
因子:
-
Vuex优势:相比sessionStorage,存储数据更安全,sessionStorage可以在控制台被看到。
-
Vuex劣势:在刷新页面后,vuex会重新更新state,所以,存储的数据会丢失。
言而总之:** **
实际问题:在vue项目中,使用Vuex做状态管理时,调试页面时,刷新后state上的数据消失了,该如何解决?
解决思路:将state中的数据放在浏览器sessionStorage和localStorage和vuex 扩展插件
store下面的index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
//1.安装插件
Vue.use(Vuex)
//2.创建对象
//根 只能根进行new Vuex.Store
const store =new Vuex.Store({
state:sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')):{
userInfo:{}//用户信息
},
mutations:{
login(state,payload) {
console.log(payload)
state.userInfo = payload
}
},
actions:{ //进行异步的操作,类似于mutations,也可以传递参数,state变成了context上下文
},
getters:{
},
modules:{
},
})
//导出store对象共享
export default store
在登陆页面的方法里面赋值
login() {
this.$refs.loginFormRef.validate(async valid=>{
//先验证
if(!valid) return;
//返回值是 promise用 await 和async 异步
//解构
let params= { username:this.loginForm.username,
password:this.loginForm.password}
console.log(this.loginForm.username)
const {data:res} =await this.$http.post("/hr/doFindHrByUsername",this.$qs.stringify(params)
);
if(res.state !==1) return this.$message.error('登录失败,用户名或密码错误')
this.$message.success('登录成功'+res)
this.$store.commit('login',res.data)
//console.log(this.$store.state.userInfo)
// 1. 将登录成功之后的 token,保存到客户端的 sessionStorage 中
// 1.1 项目中除了登录之外的其他API接口,必须在登录之后才能访问
// 1.2 token 只应在当前网站打开期间生效,所以将 token 保存在 sessionStorage 中
console.log(res)
//window.sessionStorage.setItem("token",res.data.token);
//2.通过编程式导航跳到后台主页,路由地址是 /home
this.$router.push("/home")
});
}
home页面里面存储
<span >{{this.$store.state.userInfo.username}}</span>
mounted(){
window.addEventListener('unload', this.saveState)
},
methods:{
saveState() {
sessionStorage.setItem('state', JSON.stringify(this.$store.state))
},
logout() {
window.sessionStorage.clear();
this.$router.push('/login');
},