Search code examples
vue.jsaxiosvue-cli

use axios globally in all my components vue


I am testing with axios within a Vue application and the CLI. I've been using vue-resource and I could access it on all my components by simply passing it to Vue.use (VueResource). How can I achieve this with axios, so I do not have to import it into a component, but simply define it once in the main.js file?


Solution

  • In main.js you can just assign Axios to $http.

    main.js

    import Axios from 'axios'
    
    Vue.prototype.$http = Axios;
    

    By modifying the vue prototype, any vue instance will have the ability to call $http on this. (e.g. this.$http.get('https://httpbin.org/get')

    Note: $http is the axios object now, so any method you can call on axios object, you can call on this.$http.