解决vue跨域axios异步通信 - Go语言中文社区

解决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:等待。

版权声明:本文来源博客园,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.cnblogs.com/lianjy/p/10721374.html
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-11-17 16:09:44
  • 阅读 ( 1196 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢