Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file named api.js
, housing a simplistic API class.
The contents of 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 utilize this function effectively, I structured my code by creating a dedicated folder named models
. Each model, such as User.js
and Activity.js
, has its own JS file within this folder.
The content of 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 called this method within my Login.vue
component.
The SignIn method in 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;
}
}
My directory structure looks like this:
js
│ api.js
│ app.js
│ bootstrap.js
│ router.js
│
├───components
│ │ App.vue
│ │
│ └───pages
│ Activities.vue
│ Login.vue
│ Main.vue
│ Settings.vue
│
└───models
User.js
Everything functions smoothly when the credentials are correct. However, Axios throws exceptions when there's an error, preventing me from accessing error messages in Login.vue
. How can I restructure my code to display backend errors in components while keeping the API call codes separated in different files?
I created this code structure based on some research and personal experience. Any suggestions for improving the organization of these codes would be greatly appreciated!