学做网站能赚多少,免费网站导航建设,设计公司起名大全免费,创业做网站失败Vue3按顺序调用新增和查询接口 一、前言1、代码 一、前言
如果你想将两个调用接口的操作封装在不同的方法中#xff0c;你可以考虑将这两个方法分别定义为异步函数#xff0c;并在需要时依次调用它们。以下是一个示例代码#xff1a;
1、代码
templatediv你可以考虑将这两个方法分别定义为异步函数并在需要时依次调用它们。以下是一个示例代码
1、代码
templatedivbutton clickaddAndFetch新增并查询/buttonp v-ifloading加载中.../pdiv v-ifresulth2{{ result.title }}/h2p{{ result.body }}/p/divp v-iferror{{ error }}/p/div
/templatescript
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 方法中依次调用这两个封装的方法以实现新增并查询的操作。
这种方式使代码更加模块化和可维护每个方法都负责一个特定的功能降低了代码的复杂度。