码迷,mamicode.com
首页 > 其他好文 > 详细

vue 中使用vuex和localStorage保存登录状态

时间:2020-04-22 11:32:09      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:信息保存   获取   保存   信息   inf   体验   用户信息   null   修改   

需求:

  在写vue时,将用户信息保存在vuex中,但是F5刷新之后,用户信息没有了,需要重新登陆。每次都重新登陆会导致用户体验不好。

原理:

  vuex中的数据在页面刷新之后其中的数据会初始化,这就导致组件之间通过vuex传递的数据在用户F5刷新页面之后会丢失

 

解决办法:使用vuex和localStorage保存登录状态

话不多说,上代码!!!

vuex中:

const state = {
        //先去localStorage中获取数据
    userInfo: JSON.parse(localStorage.getItem("userInfo")) || {},
}
const mutations = {
    setuserInfo(state, v) {
               //将传递的数据先保存到localStorage中
        localStorage.setItem(‘userInfo‘, JSON.stringify(v));
              // 之后才是修改state中的状态
        state.userInfo = v;
    },
}
                        

组件中逻辑:在登录成功之后提交mutations,更改用户信息

    if(res.data.code === 0){
        this.user = res.data.data
        this.$store.commit("setuserInfo", this.user);
        this.$Message[‘success‘]({
                    background: true,
                    content: ‘登陆成功,即将跳转...‘
        });
        this.$router.push(‘/chat‘)
    }

组件中逻辑:退出也要更新信息(注意不要写成null,要写成‘‘

this.$store.commit(‘setuserInfo‘,‘‘);//更新userInfo

 

vue 中使用vuex和localStorage保存登录状态

标签:信息保存   获取   保存   信息   inf   体验   用户信息   null   修改   

原文地址:https://www.cnblogs.com/yaya-003/p/12750819.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!