vue axios

vue中使用axios进行一步http访问

引入

npm install axios

main.js中

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

使用

getMess(){
      this.axios.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })
}

GET

this.axios.get('/user', {//url
params: {//数据
    id: 123
  }
})
.then(function (response) {
    console.log(response);//成功结果
})
.catch(function (error) {
    console.log(error);//失败信息
});

POST

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

并发请求

function getUserAccount() {
    return axios.get('/user/12345');
}
 
function getUserPermissions() {
    return axios.get('/user/12345/permissions');
}
 
this.axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
    //两个请求现已完成
}));

this指向

原本vue里this指向vue,但是axios里不是,所以会导致this内容报空。可以在method调用axios的函数开头加上let that=this,然后使用that代替this。

你可能感兴趣的:(vue axios)