Inside my Vue.js application, I have created a method for logging in users. This method sends a POST request to the server with the username and password, stores the returned data in Vuex store, and then redirects the user to the home page:
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
}
Here are some example mutations used in the application:
setToken: function (state, token) {
state.token = token;
},
setUsername: function (state, username) {
state.username = username;
},
In the App.vue
(root component), the values stored in Vuex are retrieved as computed properties:
computed: {
isAuthenticated () {
return this.$store.state.isAuthenticated;
},
token () {
return this.$store.state.token;
} ,
An issue arises when the page is redirected to /home
, causing all stored values to be emptied. Even though the login process is successful and the values are set in the Vuex store before redirection, they get lost upon arrival at the home page. I am seeking assistance in understanding why this occurs and how to resolve it.
UPDATE:
I am using vue-router with designated routes defined in 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},
]