vue axios

參考網址地html

https://www.runoob.com/vue2/vuejs-ajax-axios.htmlvue

https://www.jianshu.com/p/7a9fbcbb1114ios

https://www.kancloud.cn/yunye/axios/ajax

axios 發送ajax請求npm

1、下載json

npm install axios --saveaxios

2、配置
在main.js中配置後端

main.jsapi

import axios from 'axios'

Vue.prototype.$axios = axios;

 3、使用app

一、get請求

應用場景:初始化路由,獲取數據,通常與生命週期的mounted一塊兒使用

格式:

注意:this在then中function的變化

this.$axios.request({
  method: '',
  url: ''
}).then(function (arg) {
  console.log(arg)
}).catch(function (arg) {
  console.log(arg)
})

例子:

export default {
    name: "Course",
    data(){
      return {
        msg: "課程",
        courseList:[
        ]
      }
    },
    methods: {
      initCourse() {
        var that = this;
        // get請求
        this.$axios.get('http://127.0.0.1:8000/api/v1/course/')
          .then(function (response) {
            // console.log(response.data);
            if (response.data.code === 1000){
              that.courseList = response.data.data;
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
      mounted() {
        this.initCourse();
      }
}

或使用下面的方式(推薦)

this.$axios.request({
  url:http://127.0.0.1:8000/api/v1/course/',
  method:'GET'
}).then(function (arg) {
  if(arg.data.code === 1000){
    that.detail = arg.data.data
  }else{
    alert(arg.data.error)
  }
}).catch(function (ret) {
    // ajax請求失敗以後,獲取響應的內容
})

GET請求的url,含有參數

// 直接在 URL 上添加參數 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 也能夠經過 params 設置參數:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

var that = this
this.$axios.request({
  url:/user,
  method:'GET',
  params:{
    token:1234
  }
}).then(function (arg) {
     console.log(arg)
  }.catch(function (error) {
    console.log(error);
  });
})

三、post請求

應用場景:向後端提交數據(先後的數據交互用json)

格式:

this.$axios.request({
  method: 'POST',
  url: '',
  // 提交的數據
  data: {
    username: this.username,
    password: this.password
  },
  // 自定義請求頭的格式
  headers: {
    'Content-Type': 'application/json'
  }
}).then(function (arg) {
  console.log(arg)
}).catch(function (arg) {
  console.log(arg)
})