栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

本文实例为大家分享了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}}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/75516.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号