【问题标题】:Avoid that when refreshing the page, the global status is lost with Vuex and VueRouter避免刷新页面时,使用 Vuex 和 VueRouter 丢失全局状态
【发布时间】:2018-09-17 18:28:18
【问题描述】:

我正在创建一个 SPA,作为客户端会话的一个基本示例,我使用 Vuex 来存储一个布尔状态,无论用户是否登录,它都可以正常工作,而无需手动更新浏览器.当状态重新启动到其初始状态时,有什么方法可以防止这种情况发生,还是应该始终使用本地存储?如果是,如何获取存储的初始状态?

组件导航栏

<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

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

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')

在我的登录组件中,我使用 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('/');
                })

【问题讨论】:

    标签: javascript vue.js vue-router vuex


    【解决方案1】:

    如果您想在页面重新加载、浏览器会话等之间保留状态,您将需要始终使用持久存储机制。您可以使用 localStorage、sessionStorage、cookie、indexeddb... 最适合您的需求,尽管 sessionStorage当然只适用于当前会话。

    要恢复初始状态,请使用 Vuex 插件,例如 vuex-peristedstate。这将为您保存/恢复 vuex 到存储。

    例如,创建vuex-persistedstate 的实例以在您的商店中使用很简单:

    import createPersistedState from 'vuex-persistedstate'
    
    const store = new Vuex.Store({
      // ...
      plugins: [createPersistedState()]
    })
    

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 2019-02-09
      • 2020-01-20
      • 2018-11-17
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2014-06-25
      相关资源
      最近更新 更多