我使用的是vue-cli+axios的组合,下面我想记录一下如何在vue-cli中使用axios:
将终端移至项目目录下,输入
npm install axios
当出现如下图时则表示axios已经下载成功:
在vue-cli目录中的main.js中:加入以下两行代码:
import axios from 'axios'
Vue.prototype.$axios=axios;
添加到main.js的位置应如图所示:
除此之外还可如图中所示添加baseUrl:
this.$axios.defaults.baseURL='地址'
这样就完成了在vue-cli中的配置
我们将一个完整的axios写在某个组件的created()函数中:
let _this=this; this.$axios({ method:'get', url:'/MainPage/listAllSorts' }).then(function (response) { _this.$data.typeInfo=response.data; }).catch((function (error) { console.log(error.response.data); }));
在vue-cli中用此方法使用axios,首先要用this.$axios调用,其中各参数为:
以上是一个最简单的请求实例,没有发送数据,如果需要发送参数,则可以使用:
下面一个简单的示例:
let _this=this; this.$axios({ method:'get', url:'/MainPage/listAllSorts', data:{ key:1231 } }).then(function (response) { _this.$data.typeInfo=response.data; }).catch((function (error) { console.log(error.response.data); }));
在这个例子中key是以json的方式传给后端
let _this=this; this.$axios({ method:'get', url:'/MainPage/listAllSorts', params:{ key:1231 } }).then(function (response) { _this.$data.typeInfo=response.data; }).catch((function (error) { console.log(error.response.data); }));
此例中key被标识在url上,相当于:
http://基地址/MainPage/listAllSorts?key=1231
除此之外还有很多的参数可以添加,在这就不赘述了,各位可以去官网查看