本文實(shí)例為大家分享了Vue使用localStorage+Vuex保存用戶(hù)登錄信息的具體代碼,供大家參考,具體內(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 // 把登錄的用戶(hù)的名保存到localStorage中,防止頁(yè)面刷新,導(dǎo)致vuex重新啟動(dòng),用戶(hù)名就成為初始值(初始值為空)的情況 localStorage.setItem('user_name', user_name) }}const state = { user_name: '' || localStorage.getItem('user_name')}// getters 只會(huì)依賴(lài) 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)到首頁(yè),同時(shí)將token保存到localstorage中, 將登錄名使用vuex傳遞到Home頁(yè)面 if(res.meta.status === 200){ // 提示成功信息 this.$message({ message: res.meta.msg, type: 'success' }); var that = this; // 跳轉(zhuǎn)到首頁(yè) setTimeout(function(){ that.$router.push({name:'Home'}) },1000) localStorage.setItem('token',res.data.token) // 將登錄名使用vuex傳遞到Home頁(yè)面 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}}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注