Vue3按顺序调用新增和查询接口

Vue3按顺序调用新增和查询接口


一、前言

如果你想将两个调用接口的操作封装在不同的方法中,你可以考虑将这两个方法分别定义为异步函数,并在需要时依次调用它们。以下是一个示例代码:

1、代码

<template>
  <div>
    <button @click="addAndFetch">新增并查询</button>
    <p v-if="loading">加载中...</p>
    <div v-if="result">
      <h2>{{ result.title }}</h2>
      <p>{{ result.body }}</p>
    </div>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

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

export default {
  setup() {
    const loading = ref(false);
    const result = ref(null);
    const error = ref('');

    // 封装新增接口调用
    const addPost = async () => {
      try {
        const addResponse = await axios.post('https://jsonplaceholder.typicode.com/posts', {
          title: 'New Post',
          body: 'This is a new post.',
          userId: 1,
        });
        return addResponse.data;
      } catch (err) {
        throw new Error('新增操作失败');
      }
    };

    // 封装查询接口调用
    const fetchPost = async (postId) => {
      try {
        const fetchResponse = await axios.get(`https://jsonplaceholder.typicode.com/posts/${postId}`);
        return fetchResponse.data;
      } catch (err) {
        throw new Error('查询操作失败');
      }
    };

    // 新增并查询操作
    const addAndFetch = async () => {
      loading.value = true;
      try {
        // 调用新增接口方法
        const addedPost = await addPost();
        // 调用查询接口方法
        result.value = await fetchPost(addedPost.id);
      } catch (err) {
        error.value = err.message;
      } finally {
        loading.value = false;
      }
    };

    return {
      loading,
      result,
      error,
      addAndFetch,
    };
  },
};
</script>

在这个示例中,我们将新增接口调用封装在 addPost 方法中,将查询接口调用封装在 fetchPost 方法中。然后,在 addAndFetch 方法中依次调用这两个封装的方法,以实现新增并查询的操作。

这种方式使代码更加模块化和可维护,每个方法都负责一个特定的功能,降低了代码的复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

和烨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值