In recent time, I have been seeing many developers asking how to handle AJAX requests and API calls with Vue.
Vue is very flexible and doesn’t have any rule for that and leaves the choice to you.
Where should make API calls? Mixins? Vuex Actions? Components?
let’s see all the options with their pros and cons:
Mixins: You could put it in a shared mixin and import it when you need it.
- PROS: you only load when you need it
- CONS: you have to add it as a method and therefore, mix concerns between methods used by the template and methods used for JS logic not related to the template
- Vuex Actions: You could create a Vuex action for each AJAX request
- PROS: It’s centralized and available in your components and can mutate global state
- CONS: You need to load Vuex lol. If your project doesn’t have the need for it, it’s a bit overkill to load it only for AJAX calls. Especially if you don’t commit mutations in your actions, in my opinion, it becomes an anti-pattern.
- Components: You could directly make AJAX calls in the methods of your component.
- PROS: You just use what you need and have no overload
- CONS: Your calls are scattered everywhere and it can become really hard to maintain.
As you can see, all of them have pros and cons so which one is the best?
The question you should ask yourself is: Are my API calls related to Vue?
The answer is: No, they are related to your app.
Whenever something can be abstracted: abstract it!
The solution: Create a separate JS file that you import
The solution is in fact quite easy. Your API calls need to be centralized and reusable so, For each API resource, create an API file with an object literal or a static class or just export functions that make the API calls.
Why is this better?
- If you need it in another project that isn’t a Vue project, well: it’s reusable! It’s just a JS file, right?
- If a path / URL changes in the API, it’s centralized so no need to remember in which action it was called or in which component, just go to your API file and make the changes there.
- Abstraction is always better than tightly coupled logic
Here are some screens to understand: