怎么在Vue项目中利用localStorage和Vuex保存用户登录信息

发布时间:2021-03-11 17:09:56 作者:Leah
来源:亿速云 阅读:364

怎么在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}}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. VUE:vuex 用户登录信息的数据写入与获取方式
  2. 使用vuex存储用户信息到localStorage的实例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue localstorage vuex

上一篇:SpringBoot集成JWT怎么生成token和校验

下一篇:python递归函数求n的阶乘、次数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》