Vue:(五)axios

Axios是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。axios主要是用于向后台发起请求的,还有在请求中做更多可控功能。官方不再维护vue-resource,推荐使用axios。

axios:https://www.kancloud.cn/yunye/axios/234845

(一)Axios引入

  • <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • npm install axios --save

(二)基础API

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

(三)使用

  • Get请求
  • Post请求
  • Http请求
  • 多个并发请求
  • 全局拦截器使用

(四)Get请求

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

(五)Post请求

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

(六)Http请求

http:function(){
  axios({
    url:"/user",
    method:"get",//"post"
    data:{userId:"101"},//Post
    params:{userId:"101"},//Get
    headers:{token:"http-test"}
  }).then(res=>{this.msg=res.data;})
}

(七)多个并发请求

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) {
    // 两个请求现在都执行完成
  }));

(八)全局拦截器

mounted:function(){
  // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
  // 添加响应拦截器
  axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });
}

转载于:https://www.cnblogs.com/M-M-Monica/p/10085083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值