2020-05-12 axios的使用

271 阅读1分钟

安装很简单:

yarn add axios

进入页面时进行数据请求一般放在 created/mounted 钩子函数里

一.GET请求:

    axios.get('api/getData.php',{       // 还可以直接把参数拼接在url后边
        params:{
            title:'xxx'
        }
    }).then(function(res){
        this.goodsList = res.data;
    }).catch(function (error) {
        console.log(error);
    });

二.POST请求:

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

// 注意: 如果发送请求时,发现传递的参数是对象,那么可用如下方式传参数
// var params = new URLSearchParams();
// params.append('title', 'xxx');
// params.append('id',1);
// axios.post('/user', params)
//      .then(function(res){})
//      .catch(function(error){});

注意:response.data才是真正返回的后台数据


三.执行多个异步:

1.async/await

  methods: {
    async getInitData() {
      let res1 = await this.$axios.get("http://mockjs.com/api/posts");
      let res2 = await this.$axios.get("http://mockjs.com/api/posts");
      let res3 = await this.$axios.get("http://mockjs.com/api/posts");
      this.qudao = [...res1.data.posts[0].qudao];
      this.tags = [...res1.data.posts[0].tag];
      this.group = [...res1.data.posts[0].group];
    }
  },

2.axios自带方法,类似Promise.all

//获得用户信息的请求
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) {
        //两个请求现已完成
    })
);

四.请求拦截器和响应拦截器

//请求拦截器
axios.interceptors.request.use(
  function (config) {
      // 在发送请求之前做些什么
      return config;
  },
  function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
  }
);

//响应拦截器
axios.interceptors.response.use(
  function (config) {
      // 对响应数据做点什么
      return config;
  },
  function (error) {
      // 对响应错误做点什么
      return Promise.reject(error);
  }
);

参考:雪映月圆 Vue之axios基础使用