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提交不同的一些設置
- ajax 中的
tyle
這里是method
- ajax中的
success
這里是then
且不在大括號內后面接着.
出來 catch
請失敗- axios可能會用到的參數responseType:'blob'這是讓請求的內容返回
二進制