解決vue跨域axios異步通信


在項目中,常常需要從后端獲取數據內容。特別是在前后端分離的時候,前端進行了工程化部署,跨域請求成了一個前端必備的技能點。好在解決方案很多。
在vue中,在開發中,當前使用較多的是axios進行跨域請求數據,但不少人遇到如下問題:

  • 異步通信,無法同步執行
  • 無法集中管理
  • 不便閱讀
  • 還未請求成功就調轉了
  • then里面的邏輯越來越繁雜

以往的網絡請求的寫法如下:

// main.js

// 引入axios
import axios from 'axios'
Vue.prototype.$axios = axios;
// vue頁面中的使用

// get
let url = '地址'
this.$axios.get(url,{
  params:{} // 參數信息
})
  .then((res) => {
    // 成功后執行語句
  })
  .catch((err) =>{
    // 網絡中斷或失敗執行語句
  })

// post
let url = '地址'
this.$axios.post(url,{
  // 參數信息
})
  .then((res) => {
    // 成功后執行語句
  })
  .catch((err) =>{
    // 網絡中斷或失敗執行語句
  })

或許在目前的過程中異步能夠更好的解決用戶體驗感,先加載后彈出。但總有那么一個場景我們需要大量的內容進行處理,而且前后有明顯的順序執行的關系,那么異步通信可能會對你造成不必要的問題。所以,解決運用async/await解決異步通信問題

main.js旁邊新建http.js文件

// http.js

引入axios
import axios from 'axios'

var http = {
  // get 請求
  get: function(url,params){
    return new Promise((resolve,reject) => {
      axios.get(url,{
        params:params
      })
        .then((response) =>{
          resolve(response.data)
        })
        .catch((error) => {
          reject( error )
        })
    })
  }
  // post 請求
  post: function(url,params){
    return new Promise((resolve,reject) => {
      axios.post(url,params)
      .then((response) => {
        resolve( response.data )
      })
      .catch((error) => {
        reject( error )
      })
    })
  }
}

export default http

並在main.js入口引入

// 引入http請求
import http from './http.js'
Vue.prototype.$http = http

現在就可以在頁面中使用了

// 在vue中使用

// get
async login () {
  let url = '地址'
  let params = {} // 參數
  let res = await this.$http.get(url,params)
}
// post
async login () {
  let url = '地址'
  let params = {} // 參數
  let res = await this.$http.post(url,params)
}

async 放在方法前面
await 放在$http前面就OK了

單詞示意:
async:異步。
await:等待。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM