學(xué)習(xí)做網(wǎng)站的網(wǎng)站愛站關(guān)鍵詞挖掘工具
Vue3按順序調(diào)用新增和查詢接口
- 一、前言
- 1、代碼
一、前言
如果你想將兩個(gè)調(diào)用接口的操作封裝在不同的方法中,你可以考慮將這兩個(gè)方法分別定義為異步函數(shù),并在需要時(shí)依次調(diào)用它們。以下是一個(gè)示例代碼:
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('');// 封裝新增接口調(diào)用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('新增操作失敗');}};// 封裝查詢接口調(diào)用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 {// 調(diào)用新增接口方法const addedPost = await addPost();// 調(diào)用查詢接口方法result.value = await fetchPost(addedPost.id);} catch (err) {error.value = err.message;} finally {loading.value = false;}};return {loading,result,error,addAndFetch,};},
};
</script>
在這個(gè)示例中,我們將新增接口調(diào)用封裝在 addPost
方法中,將查詢接口調(diào)用封裝在 fetchPost
方法中。然后,在 addAndFetch
方法中依次調(diào)用這兩個(gè)封裝的方法,以實(shí)現(xiàn)新增并查詢的操作。
這種方式使代碼更加模塊化和可維護(hù),每個(gè)方法都負(fù)責(zé)一個(gè)特定的功能,降低了代碼的復(fù)雜度。