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);
    });
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章