简体   繁体   中英

vue.js lifecycle and page refresh not working as expected

I need a user to stay logged in even when a page is refreshed or a link is entered in the address bar of the browser.

I created some methods for in the store to save and load the user's data to local storage.

in main.js I load the data I need in the created hook like this:

new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App),
    created() {
        this.$store.dispatch('loadUser');
        const user = this.$store.getters.getUser;
        console.log(`VUE app created. Logged-in user: ${user.username}`);
    }
});

In routes.js I have a beforeEnter hook

path: '/account',
    component: Account,
    beforeEnter: (to,from,next) => {
        const user = Store.getters.getUser;
        console.log(`Should go to /account, user is ${user.username}`);
        if (!user.username) {
            next('/');
        } else {
            next();
        }
    }

I expect the vue app creation to run before the router method but it doesn't. When I refresh the /account page the router beforeEnter hook is called first and the app creation second. So my user is unknown and instead of refreshing the /account page I am redirected to the root page with a login screen.

在此处输入图片说明

How can I get the expected/wanted behaviour when a user has logged in before and his credentials (JWT token) are in local storage, a page refresh will go to the requested page instead of being redirected and why is the router method called before the vue created hook?

My vue.js version is 2.8.2

You don't have to dispatch your action in created . Dispatch it before you get to your router.

store.dispatch('loadUser')
// create or import router
// create Vue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM