1.安装
npm install axios
2.在main.js中引入
import Axios from 'axios'
Vue.prototype.$Axios=Axios
3.get请求
this.$Axios.get('http://jsonplaceholder.typicode.com/comments',{
params:{
postId:2,
t: Date.parse(new Date()) //请求时加入时间戳防止数据缓存
}
})
.then((respons)=>{ //要使用箭头函数,用function(){}时 this=undefined
console.log(respons.data);
})
.catch((error)=>{
console.log(error);
})
4.post请求
以form-data形式传参(只要用到qs库就行了,这个是axios中已经包含了的,不需要再下载相应的包了。)
import Qs from 'qs'
this.$Axios.post('http://jsonplaceholder.typicode.com/posts',
Qs.stringify({
userId: 11,
id: 101,
t: Date.parse(new Date()) //请求时加入时间戳防止数据缓存
}),
{headers: {'Content-Type':'application/x-www-form-urlencoded'}})
.then((respons)=>{
console.log(respons);
this.object=respons.data;
})
.catch((error)=>{
console.log(error);
})
5.并发请求
function getUserAccount() {
return axios.get('/user/12345',{params:{ t: Date.parse(new Date())}});
}
function getUserPermissions() {
return axios.get('/user/12345/permissions',{params:{ t: Date.parse(new Date())}});
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
6.跨域请求数据(只能在开发环境中使用)
1)修改config中index.js文件中的
proxyTable: {
'/api': {
target: 'http://news-at.zhihu.com',//跨域访问的后端接口地址
changeOrigin: true,//是否允许跨越
pathRewrite: {
'^/api': '',
}
}
}
2)main.js中添加
Vue.prototype.$url='/api'
3)请求中写:
var url=this.$url+"/api/4/news/latest";
this.$Axios.get(url,{params:{ t: Date.parse(new Date())}})
.then((respons)=>{
console.log(respons);
})
.catch((error)=>{
console.log(error);
})
7.vue使用axios时关于this的指向问题详解
https://www.jb51.net/article/131224.htm
如有疑惑移步axios中文网:https://www.kancloud.cn/yunye/axios/234845