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 方法中依次调用这两个封装的方法,以实现新增并查询的操作。

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

相关推荐

  1. Vue3顺序调用新增查询接口

    2024-05-25 23:26:25       35 阅读
  2. vue3前端调用后端接口实现批量删除

    2024-05-25 23:26:25       38 阅读
  3. Vue3 + TS 需引入全局引入 Echarts

    2024-05-25 23:26:25       37 阅读
  4. SpringBootVue接口调用传参方式

    2024-05-25 23:26:25       51 阅读
  5. 获取新闻查询API接口

    2024-05-25 23:26:25       62 阅读
  6. Python字母顺序返回字典的键

    2024-05-25 23:26:25       62 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-25 23:26:25       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-25 23:26:25       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-25 23:26:25       87 阅读
  4. Python语言-面向对象

    2024-05-25 23:26:25       96 阅读

热门阅读

  1. 栈——顺序存储

    2024-05-25 23:26:25       38 阅读
  2. mysql内存结构

    2024-05-25 23:26:25       36 阅读
  3. 【Muduo】网络库框架模型和各模块简介

    2024-05-25 23:26:25       30 阅读
  4. C# 中的 Dictionary<TKey, TValue> 类

    2024-05-25 23:26:25       32 阅读
  5. docker system prune命令详解

    2024-05-25 23:26:25       32 阅读
  6. MySql开源闪回工具MyFlash

    2024-05-25 23:26:25       31 阅读