作者:于志军贵冰卿 | 来源:互联网 | 2022-12-10 14:21
我使用npm install axios
命令安装了axios,这是我的package.json
依赖项
"dependencies": {
"axios": "^0.18.0",
"bootstrap-vue": "^2.0.0-rc.11",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
我在我的main.js
文件中注册了axios .
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)
当我尝试在我的一个组件中使用axios时,我收到此错误:
Uncaught ReferenceError: axios is not defined
如何解决这个问题?
1> user3003238..:
Vue.use
意味着添加插件.但是,axios
它不是一个插件Vue
,因此您无法通过全局添加它use
.
我的建议是axios
仅在您需要时导入.但是,如果您确实需要全局访问它,您可能希望将其添加到原型中.
Vue.prototype.$axios = axios
然后你可以使用axios
vue 访问this.$axios
2> Sanjay..:
Solution 1 (Not recommended):
In main.js
, add this line instead of import axios from 'axios'
window.axios = require('axios');
And remove
Vue.use(axios)
Solution 2 (Recommended Approach):
Using window
is generally considered a bad practice, so you better use axios
the following way:
1) Create a folder named plugins
inside of your src
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:
import ax from 'axios'
// insert all your axios logic here
export const axios = ax
export default {
install (Vue, options) {
Vue.prototype.$axios = ax
}
}
4) In src/main.js
, add the following:
import Vue from 'vue' // You can skip this line
import VueAxios from './plugins/axios'
Vue.use(VueAxios)
Now, you can use axios as this.$axios
in your components. So something like this.$axios.get()
.
Therefore, you can import axios with the following line:
import { axios } from '@/plugins/axios'
Now, you can use axios
directly in your store.
Or you can also use it as Vuex plugin:
import { axios } from '@/plugins/axios'
const axiosPlugin = store => {
store.$axios = axios
}
new Vuex.Store({
...,
plugins: [axiosPlugin]
})
Now, you can use it as this.$axios
in Vuex.
That's it!