我有一个initial
(开始)页面,用户可以在其中按下按钮进行登录。另外,在该页面上时,我想知道用户是否已经登录,所以我正在使用mapState
访问商店的isLoggedIn
状态变量。
在代码中:
// Initial.vue
<template>
<v-container
app
fluid
>
<v-parallax
src="https://cdn.vuetifyjs.com/images/backgrounds/vbanner.jpg"
height="1000"
>
<v-layout
row
wrap
>
<!-- LOGIN-->
<v-toolbar
flat
light
dense
color="transparent"
>
<v-spacer></v-spacer>
<v-toolbar-items>
<v-btn
medium
color="lime lighten-2"
@click="login"
class="font-weight-bold title text-uppercase"
>
LOGIN
</v-btn>
</v-toolbar-items>
</v-toolbar>
<v-layout
align-center
column
>
<h1 class="display-2 font-weight-thin mb-3 text-uppercase lime--text lighten-2" >My page</h1>
<h4 class="subheading">{{isLoggedIn}}</h4>
</v-layout>
</v-layout>
</v-parallax>
</v-container>
</template>
<script>
import VContainer from "vuetify/lib/components/VGrid/VContainer";
import VLayout from "vuetify/lib/components/VGrid/VLayout";
import VBtn from "vuetify/lib/components/VBtn/VBtn";
import VToolbar from "vuetify/lib/components/VToolbar/VToolbar";
import VParallax from "vuetify/lib/components/VParallax/VParallax";
import { mapState } from 'vuex';
export default {
name: "Initial",
components: {
VContainer,
VLayout,
VBtn,
VToolbar,
VParallax
},
//Upon returning to this page isLoggedIn is false eventhough isLoggedIn has been updated to store
computed: mapState({
isLoggedIn: state => state.isLoggedIn
}),
methods: {
login() {
this.$auth.login();
},
}
}
</script>
<style scoped>
</style>
用户登录后(通过auth0
),他将被重定向到注册表单。表单提交后,数据被发送到后端,我正在调用REGISTER
动作来更新存储状态,然后重定向到/home
。这样做的代码是:
//CompleteSignup.vue
this.$store.dispatch(REGISTER,registerFormData)
.then(() => this.$router.push('/home'));
我的商店是这样:
//index.js
import Vue from 'vue';
import Vuex from 'vuex';
import {APIService} from '@/common/api.service';
import {REGISTER} from "./actions.type";
import {SET_ERROR, SET_AUTH} from "./mutations.type";
Vue.use(Vuex);
export default new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: {
errors: null,
user: {},
isLoggedIn: false
},
getters: {
currentUser(state) {
return state.user;
},
},
actions: {
[REGISTER]({commit}, registerData) {
return new Promise((resolve, reject) => {
APIService.create(registerData)
.then(({data}) => {
commit(SET_AUTH, data);
resolve(data);
})
.catch(({response}) => {
commit(SET_ERROR, response.data.errors);
reject(response);
});
});
}
},
mutations: {
[SET_ERROR](state, error) {
state.error = error;
},
[SET_AUTH](state, user) {
state.isLoggedIn = true;
state.user = user.user_id;
state.errors = {};
}
}
})
当我进入/home
时,从Vue devtools中可以看到我的商店变量已正确更新:
当我导航回到/initial
页面时,会出现问题。我希望当用户返回该视图时,computed
值{ {1}}将返回isLoggedIn
;但是我却得到了默认存储值(true
)。
为什么false
不返回mapState
存储变量的true
?
-尽管我不确定是否相关-我注意到在这种情况下,isLoggedIn
再次将所附屏幕快照的第一个vue devtools
显示为活动屏幕截图(也带有相同的时间戳) )。好像回退操作重新触发了原始状态,而不是创建新状态。