天天看點

在vue中Axios的使用總結

這個作業屬于哪個課程 2021春軟體工程實踐S班(福州大學)
這個作業要求在哪裡 軟體工程實踐總結&個人技術部落格
這個作業的目标 個人技術總結
其他參考文獻 CSDN、部落格園、簡書
目錄
  • 技術概述
  • 技術詳述
  • 遇到的問題和解決
  • 總結
  • 參考文獻和資料

概述:在前後端分離程式設計中以vue作為前端架構時使用Axios進行前後端資料互動的使用。

  • 安裝
npm install vue-axios --save
           
  • 在main.js頁面引用
import axios from 'axios'
Vue.prototype.$axios = axios
...
new Vue({
    el: '#app',
    axios,
    template: '<App/>'
})
...
           
  • 使用
this.$axios({
        method: 'get',           //方法為get或post
        headers: {
          'Content-type': 'application/json;charset=UTF-8'
        },
        data: xxxxx,             //此處為post方法傳輸的資料
        url: 'xxxxx'             //此處為後端接口url
      }).then((response) => {
        ...           
      }).catch((error) => {
        console.log(error)       //請求失敗傳回的資料
      })
           
  • 流程圖
在vue中Axios的使用總結

  • axios 解決跨域cookie丢失問題
axios.defaults.withCredentials = true;
           
  • axios 資料指派問題

發起請求時報如下錯

在vue中Axios的使用總結

axios 資料指派應使用以下兩種之一,不能混

//    const that = this
      this.$axios({
        method: 'get',           //方法為get或post
        headers: {
          'Content-type': 'application/json;charset=UTF-8'
        },
        data: xxxxx,             //此處為post方法傳輸的資料
        url: 'xxxxx'             //此處為後端接口url
      }).then((response) => {    //使用箭頭函數
        console.log(JSON.stringify(response))       //請求成功傳回的資料  
        this.forklifts = response.data.data            //将請求到的資料賦到data中
        ...            
//    }).then(function(response){    //将指向vue對象的this指派給外部方法定義的屬性,然後在内部方法中使用該屬性
//      that.forklifts = response.data.data
//      ...
      }).catch((error) => {
        console.log(error)       //請求失敗傳回的資料
      })
           

通過Axios進行前後端的資料互動使用起來還是非常簡單和友善的,絕大部分的請求套用模闆即可,遇到的跨域cookie丢失問題和資料指派問題也順利解決了。希望以後可以再深入一步地學習Axios的使用。

vue中axios基本用法——陽光之城alt

vue中使用axios的多種方式——謝大見

vue axios 資料(data)指派問題