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屋!