I am a beginner currently learning Vue.js. I am using Vue with my Laravel backend. For calling APIs I wanted to separate my API calls for different models. Therefore, I created api.js
where I have a simple API class.
File api.js
export default class API {
static async invoke(url, method, data=null, headers=null, acceptJson=true){
headers = headers || {}
if(acceptJson){
headers['Accept'] = 'application/json';
}
try{
return axios({
method: method,
url: url,
data: data,
headers: headers
});
}
catch(e){
console.log("Something went wrong while connecting to the server.");
}
}
}
To call this function, I created a models
folder where I have separate JS file for each Model such as User.js
, Activity.js
etc.
File User.js
import API from '../api';
export default class User {
/**
* Login user to the system
*
* @param username string
* @param password string
*/
static async login(username, password){
return await API.invoke('/api/login', 'POST', {
'email': username,
'password': password
});
}
}
I am calling this method from my Login.vue
component.
SingIn method in File Login.vue
async signIn(){
try{
const response = await User.login(this. Username, this.password);
if(response.status === 200){
this.$router.push('/dashboard');
}
}
catch(err){
this.loginError = err.response.data.message;
}
}
On a side note, this is my directory structure:
js
│ api.js
│ app.js
│ bootstrap.js
│ router.js
│
├───components
│ │ App.vue
│ │
│ └───pages
│ Activities.vue
│ Login.vue
│ Main.vue
│ Settings.vue
│
└───models
User.js
With this code, everything works fine when my credentials are right. But when my credentials are wrong or there is any kind of error where server responds with response codes other than 2XX, Axios throws exception.
I want to display the error from backend in my Login.vue
component but when there is an exception, the exception occurs in User.js
and code doesn't execute further due which error message is not accessible in Login.vue
. How do I structure my code in such a way that I can display my error messages in my components having my API call codes separated in different files?
Also, I came up this code structure from little bit of research about structing files in Vue.js and rest is according to my knowledge and experience. I would appreciate a better approach to organize these codes if there is something wrong in this approach.
CodePudding user response:
Entire structure seems good.
In Login.vue component instead of having separate try and catch you can try following
signIn(){
User.login(this. Username, this.password)
.then((response) => {
if(response.status === 200)
this.$router.push('/dashboard');
})
.catch((err)=>{
this.loginError = err.response.data.message
})
}