axios 基本运用

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

1、安装axios插件
npm install axios vue


2、引入axios插件ios

在main.js中引入,以下:ajax

import axios from 'axios'npm

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


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

(1)执行GET请求api

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请求promise

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中引入:vue-resource

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


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

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()同样的原理}));

相关文章
相关标签/搜索