vue项目使用localStorage+Vuex来保存用户登录信息

api.js

import axios from 'axios'
const baseURL = 'http://XXX
// 全局的 axios 默认值
axios.defaults.baseURL = baseURL
// 登录请求
const loginCheck = params => {
    return axios.post('/login', params).then(res => {
        return res.data
    })
}
export { loginCheck }

 
 

store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {}
const mutations = {
    handleUserName: (state, user_name) => {
        state.user_name = user_name
            // 把登录的用户的名保存到localStorage中,防止页面刷新,导致vuex重新启动,用户名就成为初始值(初始值为空)的情况
        localStorage.setItem('user_name', user_name)
    }
}
const state = {
    user_name: '' || localStorage.getItem('user_name')
}
// getters 只会依赖 state 中的成员去更新
const getters = {
    userName: (state) => state.user_name
}
const store = new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})
export { store }

 
 

login.vue

methods:{
    login(formName){
     this.$refs[formName].validate((valid) => {
          if (valid) {
            // 调用登录请求接口
            loginCheck(this.form).then(res=>{
            //   console.log(res);
              // 登录成功,提示成功信息,然后跳转到首页,同时将token保存到localstorage中, 将登录名使用vuex传递到Home页面
              if(res.meta.status === 200){
                // 提示成功信息
                this.$message({
                    message: res.meta.msg,
                    type: 'success'
                });
                var that = this;
                // 跳转到首页
                setTimeout(function(){
                    that.$router.push({name:'Home'})
                },1000)
                localStorage.setItem('token',res.data.token)
                // 将登录名使用vuex传递到Home页面
                this.$store.commit('handleUserName',res.data.username);
              }else{
                // 登录失败,就提示错误信息
                this.$message({
                    message: '登录失败,'+res.meta.msg,
                    type: 'error'
                });
              }
            })
          } else {
             return false;
          }
        });
    }
  }

 
 

Home.vue

 您好,{{$store.getters.username}}

 
 

转自:https://blog.csdn.net/it_cgq/article/details/83932887

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值