axios的使用

Axios 是一个基于 promise 的 HTTP 库,可以在vue中进行数据请求即响应。
安装方法:

  1. $ npm install axios
  2. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

主要的使用方法GET和POST:

import  axios from (“axios”)//在组件中引用。

get:

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

或者

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

小结: axios.get(arr1,arr2);是有两个参数,第一个是请求的地址为字符串,为必须参数,第二个是请求的配置为对象,而要传送的数据有两种写法。

1.一种是写在请求地址的?后;
2.另一种是写在第二个参数——配置对象里,此时传递的数据应params的属性值。

post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

小结: axios.post(arr1,arr2,arr3);它是有三个参数的,arr1为请求的地址,arr2为请求的数据,arr3为请求的配置文件。其中arr为必须的参数。
中结:

  .then(function (response) {
    console.log(response);
  })

是用来处理请求成功时的函数。其中response是请求返回的信息。

  .catch(function (error) {
    console.log(error);
  })

是用来处理请求失败的函数,其中error是请求失败返回的信息。
还有一种是通过axios相关的配置来创建请求。

配置创建请求

// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
.then()
.catch();;
//发送GET请求
axios({
	method: 'get',
	url:'/user/12345',
	params:{
	firstName: 'Fred',
    lastName: 'Flintstone'
    }
})
.then()
.catch();

处理并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

小结:把请求作为函数返回值,把多个函数作为一个数组,进行axios.all([]).then()调用。其中.then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 })是请求成功后的处理函数。
加油!!!
学习一种新的东西本身并不难,难就难在不知从哪里入手。
从小的点,一点一点的扣,慢慢的越扣越快,越扣越快。
就想玄幻小说里的练级一样,是不会给菜鸟级的人讲天神的知识的。不会让你有一个对修真界有一个宏观的把控。
世界太大,会把人压垮。走一步看十步,走十步看百步才是王道。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值