Member-only story
Vue.js — Three common approaches to organize your API calls
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.
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: {…