Use axios globally with the CLI of vue

0

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

    
asked by FeRcHo 06.02.2018 в 20:26
source

2 answers

1

First you must install the following dependencies to your project

  

axios

     

vue-axios

Installation with NPM

  

npm i --save axios vue-axios

Now in your "main.js"

import Vue from 'vue';
import Axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
});

After this you can use Axios in any component, for example:

methods: {
  async fetch() {
    const data = await this.axios.get('${process.env.API_BASE}/users');
    if(data) {
      console.log(data); 
    } else {
      console.log('something went wrong');
    }
  }
    
answered by 18.05.2018 в 09:16
1

You can simply install axios, with the command

npm install axios --save

Then you import it into your main.js file:

import axios from 'axios'

And you create a shortcut (also in the main.js file) to be able to use it in all your components:

Vue.prototype.$http = axios;

Now you just have to use: this. $ http to call it from your component, for example:

<script>
export default {
    data() {
        return {
            consulta: []
        }
    },
    created() {
        this.$http.get("AQUÍ LA URL A LA QUE LLAMAS")
        .then(respuesta => {
              this.consulta = respuesta.data
            })
            .catch(error => {
              console.log(error)
            })
    }
}
</script>
    
answered by 01.08.2018 в 13:25