vue3异步-vuex异步操作

lxf2023-11-07 15:30:01
摘要

前端的数据均是通过接口请求拿到的,而Vue本身不支持ajax请求,那么该怎么解决Vue中的异步请求呢?这儿提供了几种方法,希望对大家有所帮助

目录
  • 如何进行异步请求
    • 一、axiOS实现异步请求
    • 二、Vue-resource实现异步请求(和axios步骤基本相同)
  • vue接口异步请求
    • 其他方法

如何进行异步请求

一、axios实现异步请求

1.项目中安装axiox

npm install --save axios

2.在main.js中引入以供全局使用

import axios from 'axios'
//可以给axios的ajax请求设置统一的主机和端口号
axios.defaults.baseURL = "Http://157.122.54.189:8080/";
//将axios这个对象添加到Vue的原型对象中,在使用的时候就只需要使用this.对象名就可以了
Vue.prototype.$http = axios

3.axios之get请求

vue前端

<template>
    <div>
    </div>
</template>
<script>
export default {
  methods:{
      getData(){
          //axios-get请求
          this.$http.get('/getData1')
            .then(r => console.log(r))//接口调用成功返回的数据
            .catch(err => console.log(err)),//接口调用失败返回的数据
    }
  }
  mounted(){//模板或el对应的html渲染完成后再调用里面的方法
    this.getData()
  }
}
</script>
<style lang="sCSS" scoped>
    
</style>

node后端

server.get('/getData1',function(req,res){
  res.send({
    'msg':'aaa'
  })
})

请求结果:

vue3异步-vuex异步操作

4.axios之post请求

Vue前端:

提交参数的两种形态:

// 1.可以直接传入字符串 name=张三&age=19

// 2.可以以对象的形式传入{name:“三”,age:19}

<template>
    <div>
    </div>
</template>
<script>
export default {
  methods:{
      getData(){
          //axios-post请求传值
      this.$http({
          method:"post",
          url:"/getData2",
          headers:{
              'Content-type': 'application/x-www-fORM-urlencoded'
          },
          data:{
              name:'xxx'
          },
          transformRequest: [function (data) {//更改传值格式
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret.slice(0,ret.length-1)
            }],
      })
        .then(r => console.log(r))
        .catch(err => console.log(err))
    }
  }
  mounted(){//模板或el对应的html渲染完成后再调用里面的方法
    this.getData()
  }
}
</script>
<style lang="scss" scoped>
    
</style>

node后端:

server.post('/getData2',function(req,res){
  req.on("data",function(data){
      console.log(querystring.parse(decodeURIComponent(data)));
  });
  res.send({
    'msg':'bbb'
  })
})

结果:

vue3异步-vuex异步操作

vue3异步-vuex异步操作

看到这儿,你可能会疑惑,为什么post请求这么繁琐。这和axios post方法默认使用application/JSON格式编码数据有关,生成的数据格式是request payload,并不是我们常用的Form data格式(表单数据格式)。

使用这种编码方式,传递到后台的将是序列化后的json字符串,而不是我们想要的对象的形式,后端拿到的值则用原有的解析方式无法解析,则会解析出错误的数据。故而,这里前端可以现将其转化一下,转化成键值对的形式再传给后端,后端再稍作处理就可以正常使用。

当然,也可以后端去做出解决,而且解决方式更加简单一些,针对Node直接将传过来的json字符串用body-parser中间件进行解析就好。

server.post('/getData2',bodyParser.json(),function(req,res){
    console.log(req.body);
    res.send({
      'msg':'bbb'
    })
});

二、vue-resource实现异步请求(和axios步骤基本相同)

1.项目中安装vue-resource

npm install --save vue-resource

2.在main.js中引入以供全局使用

import vueResource from 'vue-resource'
Vue.use(vueResource)//这儿有所不同

3.vue-resource之get请求

this.$http.get('/getData1')
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

4.vue-resource之post请求

this.$http.post('/getData2',{name:"bbb"})
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

5.vue-resource之jsonp请求

this.$http.jsonp('/getData3')
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

注意

如果在使用jsonp之后还是无法获取到跨域的数据,前端可以使用代理的方式,假装是从同一域下请求的数据,修改config下index文件,如下图:

vue3异步-vuex异步操作

在最后调用的时候直接:

this.$http.get('/api/接口')

vue接口异步请求

 // 查列表
    async getlist (pageIndex) { 
      let data = { 
        pageIndex,
        pageSize: this.pageSize
      }
      await getCouponPageList(data).then(res => {
        const { data: { code, msg, data } } = res
        if (code === 0) {
          data.list.forEach(v => {
            v.totalAmount = ''
            v.buyerPayAmount = ''
          })
          this.tableData = data.list
          data.list.forEach(async (ele, index) => {
            if (ele.status === this.$t('已使用')) {
              let temp = await this.couponGetAlipay(ele.billDetails)
              ele.totalAmount = temp.totalAmount / 100
              this.tableData[index] = ele
            }
          })
          this.dataCount = data.total
        } else {
          this.$Message.error(msg)
        }
        this.loading = false
      }).catch(err => {
        console.log(err.message)
      })
    },
    // 根据id查列表的后几项
    couponGetAlipay (orderNo) {
      return new Promise((resolve, reject) => {
        couponGetAlipay({orderNo}).then(res => {
          const { data: { code, data } } = res
          if (code === 0) {
            resolve(data)
          }
        }).catch(err => {
          console.log(err.message)
        })
      })
    },

vue3异步-vuex异步操作

vue3异步-vuex异步操作

其他方法

一:

getData: async function() { // 同步方法
  try { // 顺序请求
    await this.getSetupList();
    await this.getRoleList();
    await this.getList();
  } catch (e) {}
}

二:

getData: async function() { // 同步方法
  try { // 顺序请求
    await this.getSetupList();
    await this.getRoleList();
    await this.getList();
  } catch (e) {}
}

三:

function login(code) {
  return new Promise((resolve, reject) => { // 同步方法
    getData1().then(response => { // 方法一
      return response // 返回正确值
    }).then((res) => {
      getData2().then((response) => { // 方法一返回正确后执行方法二
        return response // 返回正确值
      }).then((res) => {
        getData3().then(response => { // 方法二返回正确后执行方法三
          return response // 返回正确值
        }).then(res => {
          getData4().then(response => { // 方法三返回正确后执行方法四
            resolve(response ) // 方法执行完毕,抛出最后结果或进行某些操作
          }).catch(res => {
            reject('方法四返回错误')
          })
        }).catch(res => {
          reject('方法三返回错误')
        })
      }).catch(res => {
        reject('方法二返回错误')
      })
    }).catch(res => {
      reject('方法一返回错误')
    })
  })
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。