Vue 中如何处理异步请求?常用的方法有哪些?

在 Vue 中处理异步请求是常见的需求,尤其是在与后端 API 交互时。Vue 本身不提供异步请求的方法,但可以通过以下几种常用的方法来实现:

1. 使用 JavaScript 原生 fetch API

fetch 是原生 JavaScript 提供的一个用于发起网络请求的 API,它可以返回一个 Promise 对象。

示例代码

<template>
  <div>
    <button @click="fetchData">Load Data</button>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error">Error: {{ error.message }}</div>
    <div v-else>
      <ul>
        <li v-for="item in data" :key="item.id">{{ item.name }}</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const data = ref([]);
const loading = ref(false);
const error = ref(null);

async function fetchData() {
  loading.value = true;
  error.value = null;
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const jsonData = await response.json();
    data.value = jsonData;
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }
}
</script>

2. 使用 axios

axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。

示例代码

首先,安装 axios

npm install axios

然后,在 Vue 组件中使用:

<template>
  <div>
    <button @click="fetchData">Load Data</button>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error">Error: {{ error.message }}</div>
    <div v-else>
      <ul>
        <li v-for="item in data" :key="item.id">{{ item.name }}</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const data = ref([]);
const loading = ref(false);
const error = ref(null);

async function fetchData() {
  loading.value = true;
  error.value = null;
  try {
    const response = await axios.get('https://api.example.com/data');
    data.value = response.data;
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }
}
</script>

3. 使用 async/awaitXMLHttpRequest

虽然 XMLHttpRequest 已经不太现代,但仍然可以在一些旧的浏览器中使用。

示例代码

<template>
  <div>
    <button @click="fetchData">Load Data</button>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error">Error: {{ error.message }}</div>
    <div v-else>
      <ul>
        <li v-for="item in data" :key="item.id">{{ item.name }}</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const data = ref([]);
const loading = ref(false);
const error = ref(null);

async function fetchData() {
  loading.value = true;
  error.value = null;
  try {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.example.com/data', true);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          const response = JSON.parse(xhr.responseText);
          data.value = response;
        } else {
          throw new Error('Network response was not ok');
        }
      }
    };
    await new Promise((resolve, reject) => {
      xhr.onload = resolve;
      xhr.onerror = reject;
      xhr.send();
    });
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }
}
</script>

4. 使用 Vue 插件

一些 Vue 插件,如 vue-resourcevue-axios,提供了封装好的请求方法,可以简化异步请求的处理。

示例代码

使用 vue-axios 插件:

<template>
  <div>
    <button @click="fetchData">Load Data</button>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error">Error: {{ error.message }}</div>
    <div v-else>
      <ul>
        <li v-for="item in data" :key="item.id">{{ item.name }}</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);

const data = ref([]);
const loading = ref(false);
const error = ref(null);

async function fetchData() {
  loading.value = true;
  error.value = null;
  try {
    await this.$axios.get('https://api.example.com/data').then((response) => {
      data.value = response.data;
    });
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }
}
</script>

总结

处理异步请求是前端开发中的常见任务,Vue 提供了灵活的方式来集成各种 HTTP 客户端库。fetch API、axiosXMLHttpRequest 和 Vue 插件都是处理异步请求的常用方法。选择哪种方法取决于项目需求、团队习惯以及对浏览器兼容性的考虑。


最后问候亲爱的朋友们,并邀请你们阅读我的全新著作

书籍详情
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JJCTO袁龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值