简体   繁体   English

刷新页面时避免使用Vuex和VueRouter丢失全局状态

[英]Avoid that when refreshing the page, the global status is lost with Vuex and VueRouter

I'm creating a SPA, and as a basic example of sessions on the client side, I'm using Vuex to store a boolean state if the user is logged in or not, it works fine while not manually updating the browser. 我正在创建一个SPA,作为客户端会话的基本示例,我使用Vuex存储布尔状态,如果用户登录或不登录,它可以正常工作,而不是手动更新浏览器。 As the state restarts to its initial state, is there any way to prevent this or should it always use localstorage? 当状态重新启动到其初始状态时,是否有任何方法可以防止这种情况,还是应该始终使用localstorage? If so, how to get the initial state of storage? 如果是这样,如何获得初始存储状态?

Component Navbar 组件导航栏

<template>
    <div>
        <ul v-if="!isLogued">
            <router-link :to="{ name:'login'}" class="nav-link">Login</router-link>
        </ul>
        <ul  v-if="isLogued">
                <a href="#" class="nav-link">Profile</a>
                <a href="" @click.prevent="logout">Salir</a>
        </ul>
    </div>
</template>
<script>
    import {mapState,mapMutations  } from 'vuex';
    export default{
        computed : mapState(['isLogued']),
        methods:{
            ...mapMutations(['logout']),
        }
    }
</script>

Store.js Store.js

export default {
    state: {
        userLogued: {},
        api_token  : '',
        isLogued : false
    },
    mutations: {

        login( state){
            state.userLogued = JSON.parse(localStorage.getItem('usuario'));
            state.api_token = localStorage.getItem('api_token');
            state.isLogued =  true
        },

        logout(state){
            state.userLogued = {}
            state.isLogued = false
            state.api_token  = null
            localStorage.clear()
        }
    }
};

App.JS App.JS

Vue.use(VueRouter)
Vue.use(Vuex)

import store from './vuex/store';
import routes from './routes';
const router = new VueRouter({
    mode: 'history',
    routes
})

const app = new Vue({
   router,
   store : new Vuex.Store(store)
}).$mount('#app')

In my login component, I do post with axios and if it is correct I do the following 在我的登录组件中,我发布了axios,如果它是正确的,我会执行以下操作

   methods : {
        ...mapMutations(['login']),
        sendLogin(){
            axios.post('/api/login' , this.form)
                .then(res =>{
                    localStorage.setItem('api_token', res.data.api_token);
                    localStorage.setItem('user_logued', JSON.stringify(res.data.usuario));
                    this.login();
                    this.$router.push('/');
                })

You will need to always be using a persistent storage mechanism if you want to preserve state across page reloads, browser sessions, etc. You can use localStorage, sessionStorage, cookies, indexeddb... whichever best suits your needs, although sessionStorage is of course only good for the current session. 如果要在页面重新加载,浏览器会话等中保留状态,则需要始终使用持久存储机制。您可以使用localStorage,sessionStorage,cookies,indexeddb ......最适合您的需求,尽管sessionStorage当然是只对本届会议有利。

To restore the initial state, use a plugin for Vuex, such as vuex-peristedstate . 要恢复初始状态,请使用Vuex的插件,例如vuex-peristedstate This will take case of the saving/restoring vuex to storage for you. 这将保存/恢复vuex的情况下为您存储。

For example, creating an instance of vuex-persistedstate for use in your store is as easy as: 例如,创建一个vuex-persistedstate实例以便在您的商店中使用就像下面这样简单:

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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