@vue/cli使用axios报错“error 'axios' is not defined no-undef”
问题
在使用 @vue/cli 构建应用时 ,推荐使用基于 promise 的 HTTP 客户端 axios 来向服务器发起 ajax 请求,访问服务器提供的 API 并展示其数据 。 相关教程中常会这样写
mounted () {
axios
.get('http://sitename.com:8000/api/welcome')
.then(response => (this.info = response))
}
但是,在实际的 @vue/cli 项目中,直接像上面例子中这样写,会报错
error 'axios' is not defined no-undef
解决办法
首先,安装axios
npm install axios
然后,在项目的main.js文件中引入axios
import axios from 'axios';
Vue.prototype.$axios = axios;
最后,在组件中使用时,将原来的axios改为this.$axios,即
mounted () {
this.$axios
.get('http://sitename.com:8000/api/welcome')
.then(response => (this.info = response))
}
这样就能够使用axios通过get或post请求访问服务器提供的API了。
冀公网安备 13010402001886号