1、基本用法
安装:
1 cnpm i axios --save
2 在 main.js
中引入 axios:
import axios from 'axios'
Vue.prototype.$axios = axios
在组件中使用:
<script>
export default {
mounted(){
this.$axios.get('/goods.json').then(res=>{
console.log(res.data);
})
}
}
</script>
2、axios请求方法:
axios可以请求的方法:
get:获取数据,请求指定的信息,返回实体对象
post:向指定资源提交数据(例如表单提交或文件上传)
put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
delete:请求服务器删除指定的数据
比如get:
input type="button" value="get请求" class="get">
<input type="button" value="post请求" class="post">
<script>
document.querySelector(".get").onclick = function () {
axios.get("https://xiaohua.zol.com.cn/")
.then(function(response){
console.log(response);
},function(err){
console.log(err);
})
}
axios请求配置:
this.$axios.get('/goods.json',{
timeout: 3000
}).then()
3 错误处理:
比如:
this.$axios.get('/url').then(res={
}).catch(err=>{
//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
console.log(err);
})
取消正在进行的http请求:
let source = this.$axios.CancelToken.source();
this.$axios.get('/goods.json',{
cancelToken: source
}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
source.cancel('取消后的信息');