在Vue.js我有這樣的方法登錄的用戶,設置的值詮釋vuex店,然後重定向到主頁:Vuex狀態重定向
login: function() {
axios.post(this.BASE_URL + "/login", {
username: this.username,
password: this.password,
}).then((res) => {
this.$store.commit('setIsAuthenticated', true);
this.$store.commit('setToken', res.data.token);
this.$store.commit('setPhoto', res.data.photo);
this.$store.commit('setUsername', res.data.username);
window.location.href = '/home'; //<-The problem
}
例突變:
setToken: function (state, token) {
state.token = token;
},
setUsername: function (state, username) {
state.username = username;
},
在App.vue
(根組件),我只是得到從商店值作爲計算出的值:
computed: {
isAuthenticated() {
return this.$store.state.isAuthenticated;
},
token() {
return this.$store.state.token;
} ,
當我註釋掉window.location.href = '/home';
時,在Vue.js控制檯中看到登錄成功並且在商店中設置了值,但只要頁面重定向到/home
,所有商店值都將被清空。 我想知道爲什麼會發生這種情況,以及如何解決它?
更新: 我使用VUE路由器在routes.js
這樣的:
import webLogin from './components/webLogin.vue';
import showAll from './components/showAll.vue';
export default [
{path:'/', component: showAll },
{path:'/add', component: addJoke } ,
{path: '/login', component: webLogin},
]
你使用Vue的路由器? – str
是的,我使用vue路由器。 – Karlom
'window.location.href'加載一個全新的頁面。如果您需要跨頁請求提供數據,則需要將其保存在某個地方。我現在用'localStorage'去登錄 – Phil