我正在创建一个 SPA,作为客户端 session 的一个基本示例,我使用 Vuex 来存储一个 bool 值状态(如果用户已登录或未登录),它在不手动更新浏览器的情况下工作正常.当状态重新启动到初始状态时,有什么方法可以防止这种情况发生,还是应该始终使用 localstorage?如果是,如何获取存储的初始状态?
组件导航栏
<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('/');
})
最佳答案
如果你想在页面重新加载、浏览器 session 等过程中保持状态,你将需要始终使用持久存储机制。你可以使用 localStorage、sessionStorage、cookies、indexeddb ……无论哪种最适合你的需要,尽管 sessionStorage当然只对当前 session 有用。
要恢复初始状态,请使用 Vuex 插件,例如 vuex-peristedstate .这将为您保存/恢复 vuex 到存储。
例如,创建用于商店的 vuex-persistedstate
实例非常简单:
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()]
})
关于javascript - 使用 Vuex 和 VueRouter 避免刷新页面时全局状态丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49714606/