Vue-CLI項目-axios模塊先後端交互(相似ajax提交)

08.31自我總結

Vue-CLI項目-axios先後端交互

一.模塊的安裝

npm install axios --save
#--save能夠不用寫

二.配置main.js

import axios from 'axios'
Vue.prototype.$axios = axios;

三.使用

created() {  // 組件建立成功的鉤子函數
    // 拿到要訪問課程詳情的課程id
    let id = this.$route.params.pk || this.$route.query.pk || 1;
    this.$axios({
        url: `http://127.0.0.1:8000/course/detail/${id}/`,  // 後臺接口
        method: 'get',  // 請求方式
    }).then(response => {  // 請求成功
        console.log('請求成功');
        console.log(response.data);
        this.course_ctx = response.data;  // 將後臺數據賦值給前臺變量完成頁面渲染
    }).catch(error => {  // 請求失敗
        console.log('請求失敗');
        console.log(error);
    })
}

與ajax提交不一樣的一些設置vue

  • ajax 中的tyle這裏是method
  • ajax中的success這裏是then且不在大括號內後面接着.出來
  • catch請失敗
  • axios可能會用到的參數responseType:'blob'這是讓請求的內容返回二進制
相關文章
相關標籤/搜索