【发布时间】: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