vue中使用axios

npm install axios vue-axios 

安装以上两个模块

在main.js中引入模块

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios)//这两个顺序不能反,否则会报错, 调用的时候使用this.$http[methods]

将axios添加到window全局对象中

window.axios = axios

在组建中调用get请求

this.$http.get('http://jsonplaceholder.typicode.com/users').then((data)=>{
      console.log(data)
    }).catch((e)=>{
      alert(e)
    });
axios.get('http://jsonplaceholder.typicode.com/users').then((data)=>{
      console.log(data)
    }).catch((e)=>{
      alert(e)
    });

axios中携带REST参数

axios.get('index.php',{
      params:{
        id:12345,
        text:'user'
      }
    }).then((response)=>{
      console.log(response)
    }).catch((error)=>{
      console.log(error)
    })
axios({
      method: 'get',
      url: 'http://jsonplaceholder.typicode.com/users',
      // data: {
      //   firstName: 'Fred',
      //   lastName: 'Flintstone'
      // }
    }).then((data)=>{
      console.log(data)
      console.log(1)
    });

在路径中携带参数

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

post请求

axios.post('index.php',{
      id:12345,
      text:'小火柴'
    }).then((response)=>{
      console.log(response)
    }).catch((error)=>{
      console.log(error)
    })
axios({
      method: 'post',
      url: 'index.php',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    }).then((data)=>{
        console.log(data)
    })

实例创建

    let getData = axios.create({
      baseURL:'http://jsonplaceholder.typicode.com',
      timeout: 5000,
      // headers: {'X-Custom-Header': 'foobar'}
    })

    getData('/users').then((data)=>{
      console.log(data)
    }).catch((e)=>{
      console.log(e)
    })
多并发请求
   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) {
        // acct为第一个请求的结果,perms为第二个请求的结果
     }))
原文地址:https://www.cnblogs.com/tw6668/p/9100583.html