二、基础用法(get、post、put等请求方法)
axios的请求方法:get、post、put、patch、delete(常用的五种)
1、get:获取数据
letdata={id:12}axios.post('/post',data).then(res=>{console.log('res)})写法二:axios({method:'post',url:'/post',data:data}).then(res=>{console.log(res)})数据是JSON的形式
letformdata=newFormData()for(letkeyindata){formdata.append(key,data[key])}axios.post("/post",formData).then(res=>{console.log('res')})数据的形式
3、put:更新数据(所有数据推送到后端)
同get和post
put与post几乎一样,只是method不一样
4、patch:更新数据(只将修改的数据推送给后端)
5、delete:删除数据
axios({method:'delete',url:'/delete',params:{},data:{}}).then(res=>{console.log(res)})什么是并发请求?
并发请求:同时进行多个请求,并统一处理
请求的方法:
axios.all()
axios.spread()
axios.all([axios.get('/data.json‘),axios.get('/city.json‘),]).then(axios.spread((dataRes,cityRes)=>{console.log(dataRes,cityRes)}))三、进阶用法(实例、配置、拦截器、取消请求等)
1、创建axios实例
当后端接口地址有多个,并且超时时长不一样时可以创建一个axios实例
axios的配置:
1、axios全局配置
2、axios实例配置
letinstance=axios.create()instance.defaults.timeout=30003、请求配置
instance.get('data.json',{timeout:5000})优先级:请求配置>实例配置>全局配置
3、在实际开发中
实例1:
只有一个方法的数据量很大时,修改此方法的超时时长
instance1.get('/contactList',{timeout:5000}).then((res)=>{console.log(res)})//此实例应用到了baseURL、timeout:5000、method、url4、拦截器
拦截器:在请求或响应被处理前拦截它们
请求拦截器
axios.interceptors.request.use(config=>{//在发送请求前做些什么returnconfig}),err=>{//在请求错误的时候做些什么returnPromise.reject(err)}响应拦截器
axios.interceptors.response.use(res=>{//请求成功对响应数据作处理returnres//这里的res返回后是axios.get().then(res=>{})中的res}),errr=>{//响应错误做写什么returnPromise.reject(err)//这里的err返回后是axios.get().then().catch(err=>{})中的err}取消拦截器(了解,一般情况下不会取消拦截器的)
letinterceptors=axios.interceptors.request.use(config=>{config.headers={auth:true}returnconfig})axios.interceptors.request.eject(interceptors)5、错误处理
axios.get('/data.json').then((res)=>{console.log(res)}).catch(err=>{console.log(err)})实例:实际开发过程中,一般添加统一错误处理
错误处理---请求拦截器
四、axios进一步封装,在项目中的实际应用
一、新建文件/service/contactApi.js
constCONTACT_API={//例子:获取联系人列表getContactList:{method:'get',url:'/contactList'}//例子:新建联系人from-datanewContactForm:{method:'post',url:'/contact/new/form'}//例子:新建联系人application/jsonnewContactJson:{method:'post',url:'/contact/new/json'}//例子:编辑联系人editContact:{method:'put',url:'/contact/edit'}//例子:删除联系人deleteContact:{method:'delete',url:'/contact'}}exportdefaultCONTACT_API
在main.js
四、使用接口
methods:{//查询asyncgetList(){letres=awaitthis.$Http.getContactList()this.list=res.data}