Vue3按顺序调用新增和查询接口
- 一、前言
- 1、代码
一、前言
如果你想将两个调用接口的操作封装在不同的方法中,你可以考虑将这两个方法分别定义为异步函数,并在需要时依次调用它们。以下是一个示例代码:
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
方法中依次调用这两个封装的方法,以实现新增并查询的操作。
这种方式使代码更加模块化和可维护,每个方法都负责一个特定的功能,降低了代码的复杂度。