用this.$store.state.online
来记录登录状态,然后导航栏根据this.online
来显示不同的选项。this.$store.state.online
会在渲染完导航栏后发送ajax改变,也会在登录后改变。
但是无论是用mounted还是compute,当this.$store.state.online
改变时,都不会改变this.online
所以造成的现象就是,登陆完,只有刷新页面,才会更新this.online
<template>
<nav id="navbar" class="nav">
<router-link to='/' class="brand">Finn</router-link>
<ul class="nav-right">
<router-link to='/' class="nav-item">主页</router-link>
<a @click='logout' class="nav-item nav-item-link" v-if="online">退出登录</a>
<router-link to='/login' class="nav-item" v-else>登录</router-link>
</ul>
</nav>
</template>
<script>
export default {
data: function() {
return {
online: this.$store.state.online
}
},
mounted: function() {
this.$http.get('/api/user')
.then(res => { // success
if(res.body.username) {
this.$store.state.online = true;
this.online = this.$store.state.online;
} else {
// this.$router.push('/');
}
});
},
methods: {
logout: function(event) {
this.$http.get('/api/logout')
.then(res => { // success
this.$store.state.online = false;
this.online = this.$store.state.online;
});
}
}
}
</script>
登录时:
this.$http.post('/api/login', data)
.then(res => { // success
if(res.body.user) {
this.$store.state.online = true;
this.$router.push('/');
}
});
$store.state中的值只能通过mutations或actions来改变的,不能直接赋值。
https://vuex.vuejs.org/zh-cn/...