Member-only story

Vue.js — Three common approaches to organize your API calls

Liu Ting Chun
3 min readFeb 8, 2020

When building a single page application, it is very common to make API calls to communicate with the server side, such as fetching data, submitting form, etc. Yet, Vue doesn’t provide an official practice for making API calls. Hence, I have summarized three common ways people are using to organize their APIs.

Concept of Programming and Software Development — by Andrey Suslov

1. Centralize all API calls in Vuex action

This approach is heavily inspired by the React-Redux model. Instead of having separated API calls in different components, you keep everything in Vuex action. Components know only actions but not endpoints. After the API call is returned, you do some data massage and business logic. After that, you update the state and notify components about the state change.

export default new Vuex.store({
state: {
account: null
},
mutations: {
setAccount(state, account) {
state.account = account;
}
},
actions: {
async signin({ commit }, { username, password }) {
let data = await axios.get('/api/signin', {
username,
password
});
commit('setAccount', data)
}
}
}

Then somewhere in your component:

export default {
computed: {
account() {
return this.$store.state.account
}
},
...
methods: {…

--

--

Liu Ting Chun
Liu Ting Chun

Written by Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.

Responses (1)