axios 基本运用

axios是专门对ajax请求进行封装的一个插件,其返回一个promise对象,用法跟ES6的promise很相似

一、安装axios插件
npm install axios


二、引入axios插件

在main.js中引入,如下:

import axios from 'axios'

Vue.prototype.$http = axios; // 通过原型链的方式这样就可以在任何组件下调用axios


三、在代码中执行请求,没有配置请求方式时默认为GET请求

(1)执行GET请求

this.$http.get("https://www.ehometd.com/temporary/api/other/all.php?fc=bianlifile&FID=459&Class=3", {
        params: {
          ID: 459
        }
      })
      .then(response => {
        this.nowImg = response.data.Sub[460].File[0].ImgUrl; // 初始默认为第一个系列的第一张图片
        this.goods_name = response.data.Sub[460].File[0].Name;
        this.goods_style = response.data.Sub[460].File[0].Desc;
      })
      .catch(function(error) {
        console.log(error);
      });
    }


(2)执行POST请求

this.$http.post("https://www.ehometd.com/temporary/api/other/all.php?fc=bianlifile&FID=459&Class=3", {
        params: {
          ID: 459
        }
      })
      .then(response => {
        this.nowImg = response.data.Sub[460].File[0].ImgUrl; // 初始默认为第一个系列的第一张图片
        this.goods_name = response.data.Sub[460].File[0].Name;
        this.goods_style = response.data.Sub[460].File[0].Desc;
      })
      .catch(function(error) {
        console.log(error);
      });
    }

 

如果报错:ReferenceError: $http is not defined"

需要安装vue-resource插件,然后在main.js中引入:

import vueResource from 'vue-resource';
Vue.use(vueResource);


四、执行多个并发请求(同时执行多个请求语句)

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

function getUserPromise() {
  return axios.get('/user/666/promise');
}

axios.all([getUserAccount(), getUserPromise()])
.then(axios.spread(function(acct, perms){
  // 两个请求都完成时才走到这里来,跟ES6的Promise.all()一样的原理
}));

转载于:https://www.cnblogs.com/secretAngel/p/9706083.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值