How to make AJAX & API calls with Vue JS

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?

This is not a Vue problem, it’s a JavaScript architectural problem.

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:

This is a fresh install
This is the main.js file where I config axios, the AJAX library (it could be any other library or fetch API)
Here I’ve created a folder “services” and a sub folder “api” in which I have my API file for “Posts” which is basically just an object literal with methods that I export as default value of my file (ES Module)
Now, here’s how to make your API call in your component, it can be exactly the same in a Vuex action.

Leave a Reply

Your email address will not be published. Required fields are marked *