Home vue.js how to properly connect axios in vue

how to properly connect axios in vue

Author

Date

Category

this is how I include it in main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use (VueAxios, axios)
Vue.config.productionTip = false
new Vue ({
render: h = & gt; h (App),
}). $ mount ('# app')

then I try to get

mounted: function () {
  this. $ axios
  .get (
   "http://api.weatherapi.com/v1/current.json?key=ca25b9b9d5494b7b85e150619201710&q=Samara",
   )
 .then ((response) = & gt; {
  this.Wether = response;
  console.log (response.data)
 })
 .catch (console.log);
  },

and in the console it throws an error Uncaught TypeError: Cannot set property ‘axios’ of undefined


Answer 1

The dock provides examples of requests:

Vue.axios.get (api) .then ((response) = & gt; {
 console.log (response.data)
})
this.axios.get (api) .then ((response) = & gt; {
 console.log (response.data)
})
this. $ http.get (api) .then ((response) = & gt; {
 console.log (response.data)
})

Therefore, try replacing this. $ axios.get with one of these three and it should work.


Answer 2

1. To use axios in Vue , one connection option is to use the Vue prototype extension like :

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

i.e.
main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.prototype.axios = axios
Vue.config.productionTip = false
new Vue ({
render: h = & gt; h (App),
}). $ mount ('# app')

App.vue

& lt; template & gt;
 & lt; div id = "app" & gt;
  {{info}}
 & lt; / div & gt;
& lt; / template & gt;
& lt; script & gt;
export default {
 name: 'App',
  data () {
   return {
   info: []
   }
},
mounted () {
this.axios
 .get ('https://api.coindesk.com/v1/bpi/currentprice.json')
 .then (response = & gt; (this.info = response.data.bpi))
}
}
& lt; / script & gt;

2. If you want to use vue-axios then you need to take care of the package version as stated in the documentation. For your probably version vue 2. * you need to install the corresponding package vue-axios :

npm install --save axios [email protected]

after installing these packages, your above code should work fine, just replace this. $ axios with this.axios , which follows from documentation vue-axios .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions