javascriptvue.jsvuejs2axiosminix

Vue.js Global Axios Calls


I am writing a project which uses so many Axios calls from different pages. Instead of using Axios calls multiple times, is it possible to write a single Axios call function and use it in each pages.

For ex, define an "axiosCall" function once and than use it in different pages by just calling that function.

axiosCall (serviceName, parameter) {
  axios
    .get(`http://localhost/xApi/` + serviceName + `/` + parameter)
    .then(response => {
        return response.data
    })
    .catch(e => {
      this.exceptionHandler('Error at get ' + serviceName + ' : ', e)
    })
}

Then use it like

var userData = axiosCall('user',1)
var roleData = axiosCall('role',2)

Thanks in advance


Solution

  • There are a few ways to do this:

    In your bootstrap file i.e main.js you could do Vue.prototype.$axiosCall = function () { ... } before you initialise Vue then within your components you could just call this.$axiosCall('user', 1).

    Another way would be to use a mixin (axiosMixin.js):

    export default {
      methods: {
        axiosCall () { ... }
      }
    }
    

    Then include it as a global mixin in your bootstrap file like: Vue.mixin(UserMixin) (again, in your bootstrap file before the initialise has been done).