Vuex中的localStorage没有刷新

时间:2019-05-29 15:14:21

标签: laravel authentication vue.js vuejs2 vuex

我用 Vuex 编写代码以在Laravel单页应用程序中登录和注销,效果很好,但是当我登录帐户时,配置文件信息(名称,地址,电子邮件等)确实没有不会显示在个人资料中,但是在我重新加载页面后,个人资料信息会加载,并且当另一个用户尝试使用个人资料时,向他/她显示的最后一个登录用户的数据会显示

auth.js:

export function registerUser(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/register', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('Somthing is wrong!!')
        })
    })
}

export function login(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/login', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('The Email or password is incorrect!')
        })
    })
}

export function getLoggedinUser(){
    const userStr = localStorage.getItem('user');

    if(!userStr){
        return null
    }

    return JSON.parse(userStr);
}

store.js:

import {getLoggedinUser} from './partials/auth';
const user = getLoggedinUser();
export default {
    state: {
        currentUser: user,
        isLoggedIn: !!user,
        loading: false,
        auth_error: null,
        reg_error:null,
        registeredUser: null,
    },
    getters: {
        isLoading(state){
            return state.loading;
        },
        isLoggedin(state){
            return state.isLoggedin;
        },
        currentUser(state){
            return state.currentUser;
        },
        authError(state){
            return state.auth_error;
        },
        regError(state){
            return state.reg_error; 
        },
        registeredUser(state){
            return state.registeredUser; 
        },

    },
    mutations: {
        login(state){
            state.loading = true;
            state.auth_error = null;
        },
        loginSuccess(state, payload){
            state.auth_error = null;
            state.isLoggedin = true;
            state.loading = false;
            state.currentUser = Object.assign({}, payload.user, {token: payload.access_token});

            localStorage.setItem("user", JSON.stringify(state.currentUser));
        },
        loginFailed(state, payload){
            state.loading = false; 
            state.auth_error = payload.error;
        },
        logout(state){
            localStorage.removeItem("user");
            state.isLoggedin = false;
            state.currentUser = null;
        },
        registerSuccess(state, payload){
            state.reg_error = null;
            state.registeredUser = payload.user;
        },
        registerFailed(state, payload){
            state.reg_error = payload.error;
        },
    },
    actions: {
        login(context){
            context.commit("login");
        },
    }
};

general.js:

export function initialize(store, router) {
    router.beforeEach((to, from, next) => {
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        const currentUser = store.state.currentUser;

        if(requiresAuth && !currentUser) {
            next('/login');
        } else if(to.path == '/login' && currentUser) {
            next('/');
        } else {
            next();
        }

        if(to.path == '/register' && currentUser) {
            next('/');
        }

    });

    axios.interceptors.response.use(null, (error) => {
        if (error.resposne.status == 401) {
            store.commit('logout');
            router.push('/login');
        }

        return Promise.reject(error);
    });

    if (store.getters.currentUser) {
        setAuthorization(store.getters.currentUser.token);
    }
}

export function setAuthorization(token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}

我认为此问题与我的 localstorage 有关,该如何解决? 我是Vue的新手,也不知道出了什么问题。

登录组件:

<template>
<main>
    <form @submit.prevent="authenticate">
    <div class="grid-x grid-padding-x">

        <div class="small-10 small-offset-2 cell" v-if="registeredUser">
            <p class="alert success">Welcome {{registeredUser.name}}</p>
        </div>
        <div class="small-10 small-offset-2 cell" v-if="authError">
            <p class="alert error">
                {{authError}}
            </p>
        </div>

        <div class="small-2 cell">
            <label for="email" class="text-right middle">Email:</label>
        </div>
        <div class="small-10 cell">
             <input type="email" v-model="formLogin.email" placeholder="Email address">
        </div>


        <div class="small-2 cell">
            <label for="password" class="text-right middle">Password:</label>
        </div>
        <div class="small-10 cell">
             <input type="password" v-model="formLogin.password" placeholder="Enter password">
        </div>

        <div class="small-10 small-offset-2 cell">
            <div class="gap"></div>
            <input type="submit" value="Login" class="button success expanded">
        </div>
    </div>

    </form>

</main>

</template>

<script>
import {login} from '../../partials/auth';
export default {
    data(){
        return {
            formLogin: {
            email: '',
            password: ''
        },
        error: null
        }
    },
    methods:{
        authenticate(){
            this.$store.dispatch('login');

        login(this.$data.formLogin)
            .then(res => {
                this.$store.commit("loginSuccess", res);
                this.$router.push({path: '/profile'});
            })
            .catch(error => {
                this.$store.commit("loginFailed", {error});
            })
        }
    },
    computed:{
        authError(){
            return this.$store.getters.authError
        },
        registeredUser(){
            return this.$store.getters.registeredUser
        }
    }
}
</script>

2 个答案:

答案 0 :(得分:1)

本地存储数据是在页面加载时加载的,因此,当您使用setItem时,直到下一次才可见。

您应该将数据存储到vuex存储,并将其用作源。仅在页面加载时设置并从本地存储中获取数据。

否则请使用类似https://github.com/robinvdvleuten/vuex-persistedstate

的内容

答案 1 :(得分:0)

我解决了这个问题。我的EditProfile组件中有此代码。

methods: {
            getAuthUser () {
                axios.get(`./api/auth/me`)
                .then(response => {
                    this.user = response.data
                })
            },
}

this.user = response.data是错误的,我对此很怀疑:

getAuthUser () {
    this.user = this.$store.getters.currentUser
},