Doubts about the import and overall use of Axios in Vuejs

Asked

Viewed 276 times

0

I am using Axios in one of my projects with Vuejs, my doubt is directly linked to the global import form of the plugin. Currently I’m doing so:

Create a /plugin/Axios.js file with this code:

import Vue from 'vue'
import Axios from 'axios'

Axios.defaults.baseURL = 'https://minha-api/'

Vue.use({
    install(Vue) {
        Vue.prototype.$http = Axios
    }
})

And in main.js I import the above file.

I even thought about ignoring the /plugins/Axios.js and making the import directory in main.js in this way:

...
import Axios from 'axios'

Axios.defaults.baseURL = 'https://api.cartolafc.globo.com/'

Vue.prototype.$http = Axios
....

If possible I would still like to understand what that would be:

Vue.use({
    install(Vue) {

2 answers

3


To documentation explains how to use/create plugins, but basically works like this:

To use a plugin you need "install" it in its instance using the method Vue.use(). This global method will call the method MeuPlugin.install() when a plugin is installed (see in the source code of Vue.js).

So the simplest explanation is that the method install would be like a callback, or maybe a, "builder" plugin so that when the programmer decides to use it in your application this method performs all preparations so that the plugin works properly when it is used.


In the source code of Vue.use() has the code:

if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
      plugin.apply(null, args)
}

That is, you can pass an object that has the method install or pass a class that will be instantiated.

So to create a plugin you could use an object with a property install that is a function

let meu_plugin = {
    install: function(Vue) {
        // código do plugin
    }
}
Vue.use(meu_plugin)

You could also use directly inside the Vue.use() as in the example you posted:

Vue.use({
    install: function(Vue) {
        // código do plugin
    }
})

0

That way you would be installing Axios as a plugin. It would make it easier to access it within a Component using a this.$http.get() but I believe that for a somewhat more comprehensive approach, using it as a simple Singleton would be better. Think that you may need Axios within a Vuex action for example.

  • How would this use as Singleton?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.