Nuxt.js - API 调用的最佳场所 [英] Nuxt.js - The best place for API calls
问题描述
我是 Vue.js Nuxt 和所有前端内容的新手.
I'm new to Vue.js Nuxt and all front-end stuff.
我有一个关于 API 调用的问题.我不确定什么是正确的方法,这里是最佳实践.
I have a question about API calls. I'm not sure what is the right way, the best practice here.
我有一家商店.在那个商店中,我有调用我的 API 并设置状态的操作,例如.
I have a store. In that store, I have actions that are calling my API and sets state eg.
async fetchArticle({ state, commit }, uuid) {
const response = await this.$axios.get(`articles/${uuid}/`)
commit('SET_ARTICLE', response.data)
},
这很好,它适用于一个组件.
And that is fine it is working for one component.
但是如果我只想获取文章而不改变状态怎么办.
But what if I want to just fetch the article and not changing the state.
要实现 DRY,我首先想到的是创建获取数据并在需要的地方使用的服务层.
To be DRY first thing that comes to my mind is to create the service layer that is fetching the data and is used where it is needed.
这是正确的方法吗?在哪里可以找到一些可以从中汲取灵感的真实示例?
Is it the right approach? Where can I find some real-world examples that I can take inspiration from?
推荐答案
使用存储库模式来抽象您的 API 绝对是一个好主意!无论您使用 @nuxtjs/axios
模块还是 @nuxt/http
模块,您都可以将任一实例传递给您的存储库类/函数.下面是抽象的repository.js"的真实示例.文件.
Using the repository pattern to abstract your API is definitely a good idea! Whether you use the @nuxtjs/axios
module or the @nuxt/http
module, you can pass either instance to your repository class/function. Below a real world example of an abstracted "repository.js" file.
export default $axios => resource => ({
index() {
return $axios.$get(`/${resource}`)
},
create(payload) {
return $axios.$post(`/${resource}`, payload)
},
show(id) {
return $axios.$get(`/${resource}/${id}`)
},
update(payload, id) {
return $axios.$put(`/${resource}/${id}`, payload)
},
delete(id) {
return $axios.$delete(`/${resource}/${id}`)
}
})
然后您可以创建一个插件来为您的端点初始化所有不同类型的存储库:
You can then create a plugin to initialize all different kinds of repositories for your endpoints:
import createRepository from '~/path/to/repository.js'
export default (ctx, inject) => {
const repositoryWithAxios = createRepository(ctx.$axios)
const repositories = {
posts: repositoryWithAxios('posts'),
users: repositoryWithAxios('users')
//...
}
inject('repositories', repositories)
}
进一步阅读:在 Nuxt 中组织和解耦 API 调用.js
这篇关于Nuxt.js - API 调用的最佳场所的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!