我有一个 Vue3 应用程序,我在其中使用以下 API 调用方法:
- 有一个
api
文件夹,里面有直接调用后端的函数。例如:
export async function getCourses(): Promise<Course[]> {
const response = await axios.get(`/courses/`);
return response.data;
}
export async function getCourse(courseId: string): Promise<Course> {
const response = await axios.get(`/courses/${courseId}/`);
return response.data
}
export async function getExercises(courseId: string): Promise<Exercise[]> {
const response = await axios.get(`/courses/${courseId}/exercises/`);
return response.data
}
有一个 Vuex 存储,其操作调用
api
文件夹中的这些函数并将数据提交到存储的状态Vue 组件访问存储状态并向其分派(dispatch)操作以检索数据
这种方法的问题是 api
函数变得极其重复。我必须定义 4 个不同的函数才能在实体上启用 CRUD,并且所有函数都采用几乎相同的参数(例如,在我的应用程序中,所有资源都是类(class)的子资源,因此需要用于获取的 courseId
参数)并具有相同的结构(等待 axios 调用并返回响应的 data
)。
我更喜欢一种方法,其中我以声明方式定义路由和它们期望的参数(就 id 等 url 组件而言),然后能够安全地执行如下操作:
getApiService().courses(courseId).delete() // deletes a course
getApiService().courses(courseId).exercises().get(exerciseId) // returns an exercise
getApiService().courses(courseId).exercises().post(payload) // creates and returns an exercise
getApiService().courses(courseId).exercises().get(exerciseId).choices().list() // returns the list of choices for an exercise
// and so on
什么是实现这一目标的好方法?是否有任何现有的软件包可以为 Vue3 执行此操作?
最佳答案
您正徘徊在中间地带,想要稍微改进全局最受欢迎的行业标准库的界面。 不要这样做!它充满了陷阱。您想要的界面在代码(类(class))中包含您的概念,因此只有您才能编写它。但是您编写的内容将是不稳定且不完整的,并且一旦您需要处理错误情况或添加自定义 header ,就会妨碍您。我活得越久,我越觉得每个人的项目都应该厚一层。当你开始调用自己的代码时,请立即扪心自问。使用这些出色的库、vue、axios 等,并惊叹于它们为您做了多少事情以及它们的界面是多么简洁。以前的情况要糟糕得多。为了简单、清晰、易于维护,一点点重复是值得的。
关于javascript - Vue3 - 如何避免 API 调用中的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73330697/