本文实例为大家分享了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}}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
offset、client、scroll (width,height、left,top、X,Y)
网友评论