1. 程式人生 > >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}}