Vue前端框架学习(三):使用axios进行数据请求

Vue前端框架学习(三):使用axios进行数据请求

axios的简介

axios是一个基于promise的HTTP库,用于数据请求。它有一下特性:

  • 支持promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御XSRF

由于现在官方已经不再更新vue-resource库,我们改为用axios进行数据请求。

axios的安装

可参考axios中文网:http://www.axios-js.com/zh-cn/

在前面的教程中,已经使用vue-cli创建了vue项目,接下来在项目根目录下,我们可以选择安装axios,也可以选择安装基于vuejs轻度封装的vue-axios,我选择安装vue-axios:

npm install --save axios vue-axios

然后再项目的main.js文件内,按以下顺序引入axios:

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

Vue.use(VueAxios, axios)

axios的使用

post方式

一下是在注册中使用axios进行数据请求,请求方式为post,数据类型为form-data

handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          var params = new FormData();
          params.append("username", this.registerForm.username);
          params.append("password", this.registerForm.password);
          params.append("name", this.registerForm.name);

          var config = {
            headers: {
              "Content-Type": "multipart/form-data"
            }
          };

          var url = this.$store.state.baseUrl + "/register/";

          //缓存this指针
          var self = this

          this.axios
            .post(url, params, config)
            .then(function(response) {
              //用户名已存在
              if (response.data.error_code == 21) {
                self.$message.error(response.data.message);
              }
              // 成功
              else if (response.data.error_code == 0) {
                self.$router.push({ path: "/" });
              }
            })
            .catch(function(error) {
              self.$message.error(error);
            });
        } else {
          this.$message.error("输入不符合规范!!");
          return false;
        }
      });
    },

get方式

携带参数并使用get方式时,参数会体现在url中,比如:

axios.get('/user?ID=12345')

就相当于

axios.get('/user', {
  params: {
    ID: 12345
  }
})

示例如下:

getCourseInfo() {
  var myParams = {
    course_id: this.$route.query.course_id
  };

  var courseInfoUrl = this.$store.state.baseUrl + "/course/query";
  var self = this;

  this.axios
    .get(courseInfoUrl, { params: myParams })
    .then(function(response) {
      if (response.data.error_code == 0) {
        self.course_name = response.data.data.course_name;
        self.course_introduction = response.data.data.course_introduction;
        self.course_category = response.data.data.course_category;
        self.course_tag = response.data.data.course_tag;
        self.course_cover = response.data.data.course_cover;
        self.course_attendance = response.data.data.course_attendance;
      } else if (response.data.error_code == 31) {
        self.$message.error(this.$store.state.errorText31);
      } else {
        self.$message.error(this.$store.state.errorTextUnknown);
      }
    })
    .catch(function(error) {
      self.$message.error(error);
    });
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章