Reputation: 184
I have a piece of code (auth.js) that is supposed to be triggered after a user successfully logs in. But I noticed that 2 lines do not seem working. it is not tiggered.
this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token; and this.$eventHub.$emit('userLoggedIn');
is there something i need to do to make both work? i have set them up to be accessible globally. i checked out the line: localStorage.setItem('user', JSON.stringify(user)); and seems to work fine.
i have tried remove this word but to no avail.
main.js
import auth from '@/auth'
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.prototype.$auth = auth
Vue.prototype.$eventHub = new Vue();
auth.js
class Auth {
constructor() {
this.token = null;
this.user = null;
}
login(token, user) {
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(user));
this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
this.token = token;
this.user = user;
this.$eventHub.$emit('userLoggedIn');
}
check() {
return !! this.token;
}
}
export default new Auth();
this is the code inside my Login.vue which calls the auth.js login method:
login() {
let data = {
email: this.username,
password: this.password
};
this.$axios.post('http://127.0.0.1:8000/api/login', data)
.then(({data}) => {
if (data.status == 200) {
this.$auth.login(data.data.token, data.data.user);
this.$router.replace('about');
} else {
// console.log("Error");
}
})
.catch(() => {
//alert(response.data.message);
});
}
Upvotes: 0
Views: 39
Reputation: 647
The this
keyword in the Auth class is not pointing to the Vue instance. You can pass the Vue instance as a parameter of login method like this:
class Auth {
constructor() {
this.token = null;
this.user = null;
}
login(vue, token, user) {
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(user));
vue.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
this.token = token;
this.user = user;
vue.$eventHub.$emit('userLoggedIn');
}
check() {
return !! this.token;
}
}
export default new Auth();
And then call login method this way:
this.$auth.login(this, data.data.token, data.data.user);
Upvotes: 1