当前位置: 首页 > Web前端 > vue.js

Axios基本用法

时间:2023-03-31 21:18:05 vue.js

AXIOS基本用法Axios是一个基于Promise的HTTP库,可以在浏览器和node.js中使用。推荐使用axios在vue中实现ajax。一个简单的GET例子json_demo.json').then(response=>(this.info=response.data.sites)).catch(function(error){//请求失败console.log(error);});}})两者传参方法如下//直接在URL中加上参数ID=12345axios.get('/user?ID=12345').then(function(response){console.log(response);})。catch(函数(错误){console.log(错误);});//也可以通过params设置参数:axios.get('/user',{params:{ID:12345}}).then(function(response){console.log(response);}).catch(function(错误){console.log(错误);});对于POST方法newVue({el:'#app',data(){return{info:null}},mounted(){axios.post('https://www.runoob.com/try/ajax/demo_axios_post.php').then(response=>(this.info=response)).catch(function(error){//请求处理失败console.log(error);});}})POST参数axios.post('/user',{firstName:'Fred',//参数firstNamelastName:'Flintstone'//参数lastName}).then(function(response){console.log(response);}).catch(function(error){console.log(error);});对于多个并发请求functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){//现在执行两个请求}));axiosAPI可以通过将相关配置传递给axios来创建请求axios(config)//发送POST请求axios({method:'post',url:'/user/12345',data:{firstName:'Fred',lastName:'Flintstone'}});//GET请求remote图片axios({method:'get',url:'http://bit.ly/2mTM3nY',responseType:'stream'}).then(function(response){response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});axios(url[,config])//发送GET请求(默认方式)axios('/user/12345');请求方法别名使用方便,官方支持所有请求方法提供别名,可以直接使用别名发起请求:axios.request(config)axios.get(url[,config])axios.delete(url[,config])axios.head(url[,config])axios.post(url[,data[,config]])axios.put(url[,data[,config]])axios.patch(url[,data[,config]])并发处理并发请求的辅助函数:axios.all(iterable)axios.spread(callback)