I installed axios using the npm install axios
command this is my package.json
dependencies
"dependencies": {
"axios": "^0.18.0",
"bootstrap-vue": "^2.0.0-rc.11",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
I registered the axios in my main.js
file.
import Vue from 'vue'
import VueRouter from 'vue-router'
import BootstrapVue from 'bootstrap-vue'
import axios from 'axios'
import App from './App'
import routerList from './routes'
Vue.use(axios)
Vue.use(BootstrapVue)
Vue.use(VueRouter)
When I tried to use axios in one of my components I get this error:
Uncaught ReferenceError: axios is not defined
How to fix this?
then inside your component you can start using axios like this:
Solution 1 (Not recommended):
In
main.js
, add this line instead ofimport axios from 'axios'
And remove
Solution 2 (Recommended Approach):
Using
window
is generally considered a bad practice (it's funny thatLaravel
actually uses this way), so you better useaxios
the following way:1) Create a folder named
plugins
inside of yoursrc
directory.2) Then, create
axios.js
file inside that directory. We will put all our axios logic here and use axios as a Vue plugin.3) Add the following:
4) In
src/main.js
, add the following:Now, you can use axios as
this.$axios
in your components. So something likethis.$axios.get()
.However, in Vuex, you cannot access
this
so you have got to importaxios
fromplugins/axios.js
file.Therefore, you can import axios with the following line:
Now, you can use
axios
directly in your store.That's it!
Vue.use
means adding plugins. However,axios
is not a plugin forVue
, so you can not add it globally viause
.My recommendation is importing
axios
only when you need it. But if you really need to access it globally, you may like to add it to prototype.Then you can access
axios
in vue usingthis.$axios
Try this codes:
i found in laravel project
window.axios = require('axios');
when i insert it in myproject. that all be fine!Also install
vue-axios
and import inmain.js
Then in
main.js
:Now if I am not mistaken in your methods you can use for example: