Home » vue » How to assign Axios globally in Vue js?

How to assign Axios globally in Vue js?

Posted by: admin November 26, 2021 Leave a comment

Questions:

How do I assign Axios globally in Vue js?

I am trying to load Axios so that I can access it in any component.

I am trying as follows:

main.js

import axios from 'axios'
Vue.prototype.$axios = axios

home.js

buyers(data) {
    return new Promise(function (resolve, reject) {
        this.$axios.get(`/buyers?${data}`)
            .then(response => {
                resolve(response.data)
            })
            .catch(error => {
                reject(error.response.data)
            })
    })
}

index.vue?6ced:203 Uncaught (in promise) TypeError: Cannot read
property ‘$axios’ of undefined

Answers:

I think you’re looking for something like this:

buyers(data) {
  return this.$axios.get(`/buyers?${data}`)
    .then(response => {
      return response.data
    })
    .catch(error => {
      throw error.response.data
    })
  })
}

Generally if you find yourself creating a new Promise using the constructor you’re probably doing something wrong. That should only be required when wrapping other code that doesn’t use Promises.

The reason for the error you were seeing is that the extra function changes the value of this. Every time you enter a new function the value of this changes.

You could also fix it by changing this line:

return new Promise(function (resolve, reject) {

to this:

return new Promise((resolve, reject) => {

Using an arrow function would preserve the surrounding this value, so that it still refers to the component.

###

Try this:

install(vue, opts) {
      vue.prototype.$axios = $axios;
    }

Then Vue.use($axios) if you want globally