一。npm安装axios
npm install axios --save
二。引用与简单调用
<template>
<div>
a页面<router-link to="/">返回</router-link>
</div>
</template>
<script>
import Axios from 'axios'
import B from './B.vue'
export default {
components:{
B
},
created(){
Axios.get('/json/data.json').then((res)=>{
console.log(res);
})
}
}
</script>
三。get post put patch delete 并发请求
get :一般用于获取数据
post :一般用于提交数据(表单提交+文件上伟)
put:更新数据(全部的数据推送到后端)
patch:更新数据(只将修改的数据推送到后端)
delete:删除数据
并发请求:同时进行多个请求,并统一处理返回值
<template>
<div>Axios2</div>
</template>
<script>
import Axios from 'axios'
export default {
created() {
//get
Axios.get('/json/data.json').then((res)=>{
console.log(res);
})
Axios.get('/json/data.json',{params:{id:12}}).then((res)=>{
console.log(res);
})
Axios(
{
method:"get",
url:"/json/data.json",
params:{id:12}
}
).then(res=>{
console.log(res)})
//post json
//application/json
let data={
id:12
}
Axios.post('/post',data).then(res=>{
console.log(res)
})
Axios(
{
method:'post',
url:'/post',
data:data
}
).then(res=>{
console.log(res)
})
//post form-data 提交表单
let formData = new FormData()
for(let key in data){
formData.append(key,data[key]);
}
Axios.post('/post',formData).then(res=>{
console.log(res)
})
//put 类似post
Axios.put('/put',data).then(res=>{
console.log(res)
})
//patch 类似post
Axios.patch('/patch',data).then(res=>{
console.log(res)
})
//delete
Axios.delete('/delete',{
params:{id:12}
}).then(res=>{
console.log(res)
})
Axios.delete('/delete',{
data:{id:12}
}).then(res=>{
console.log(res)
})
Axios(
{
method:'delete',
url:'/delete',
params:{id:12}
}
).then(res=>{
console.log(res)
})
Axios(
{
method:'delete',
url:'/delete',
data:{id:12}
}
).then(res=>{
console.log(res)
})
//并发请 Axios.all() Axios.spread()
Axios.all([
Axios.get('/json/data.json'),Axios.get('/json/name.json')
]).then(
Axios.spread((des1,des2)=>{
//在这里统一处理返回值
console.log(des1,des2)
})
)
}
}
</script>