本文實(shí)例為大家分享了Vue使用localStorage+Vuex保存用戶登錄信息的具體代碼,供大家參考,具體內(nèi)容如下
api.js
import axios from 'axios' const baseURL = 'http://XXX // 全局的 axios 默認(rèn)值 axios.defaults.baseURL = baseURL // 登錄請(qǐng)求 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中,防止頁面刷新,導(dǎo)致vuex重新啟動(dòng),用戶名就成為初始值(初始值為空)的情況 localStorage.setItem('user_name', user_name) } } const state = { user_name: '' || localStorage.getItem('user_name') } // getters 只會(huì)依賴 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) { // 調(diào)用登錄請(qǐng)求接口 loginCheck(this.form).then(res=>{ // console.log(res); // 登錄成功,提示成功信息,然后跳轉(zhuǎn)到首頁,同時(shí)將token保存到localstorage中, 將登錄名使用vuex傳遞到Home頁面 if(res.meta.status === 200){ // 提示成功信息 this.$message({ message: res.meta.msg, type: 'success' }); var that = this; // 跳轉(zhuǎn)到首頁 setTimeout(function(){ that.$router.push({name:'Home'}) },1000) localStorage.setItem('token',res.data.token) // 將登錄名使用vuex傳遞到Home頁面 this.$store.commit('handleUserName',res.data.username); }else{ // 登錄失敗,就提示錯(cuò)誤信息 this.$message({ message: '登錄失敗,'+res.meta.msg, type: 'error' }); } }) } else { return false; } }); } }
Home.vue
您好,{{$store.getters.username}}
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com