Vue - API 调用是否属于 Vuex? [英] Vue - Do API calls belong in Vuex?

查看:18
本文介绍了Vue - API 调用是否属于 Vuex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找将 API 调用理想地放置在 vue 模块中的位置的答案.我不是在建造 SPA.例如,我的 auth 块有几个组件用于登录、密码重置、帐户验证等.每个块都使用 axios 进行 API 调用.Axios 已经提供了异步的 promise.

I am struggling with finding answer for where to ideally put API calls in vue modules. I am not building an SPA. For example my auth block has several components for login, password reset, account verifiction etc. Each block uses axios for API calls. Axios already provides promises, which are async.

问题是关于最佳实践的.API 调用是否属于 Vuex 操作?这种方法有什么优点/缺点吗?

The question is about the best pracitces. Do API calls belong in a Vuex actions? Are there any pros/cons of such approach?

将 axios 调用保留在它们所属的组件中是否有任何缺点?

Is there any drawback of keeping axios calls within the components they belong to?

推荐答案

我在服务中调用 API,而不是 Vuex 或组件.基本上,将 API 调用与商店代码混合在一起有点多方面的责任,组件应该为视图提供而不是获取数据.

I do API calls in services, not Vuex or components. Basically, mixing the API calls in with the store code is a bit too multi-responsibility, and components should be about providing for the view not fetching data.

作为一个简单服务的例子(使用 Vue.http 但对于 Axios 调用相同),

As an example of a simple service (using Vue.http but same for an Axios call),

文件服务 .js

import Vue from 'vue'

export default {
  getFileList () {
    return Vue.http.get('filelist.txt')
      .then(response => {
        // massage the response here
        return filelist;
      })
      .catch(err => console.error('getFileList() failed', err) )
  },
}

我在下面的另一个服务中使用它(层数由你决定).
请注意,外部服务正在检查存储以查看获取是否已经发生.

I use it in another service as below (the number of layers is up to you).
Note, the outer service is checking the store to see if the fetch already happened.

DataService.js

import FileService from './file.service'

checkFiles (page) {
  const files = store.state.pages.files[page]
  if (!files || !files.length) {
    return store.dispatch('waitForFetch', {
      resource: 'files/' + page,
      fetch: () => FileService.getFileList(),
    })
  } else {
    return Promise.resolve()  // eslint-disable-line no-undef
  }
},

waitForFetch 是调用传递给它的 fetch 函数的操作(由 FileService 提供).它基本上为获取提供包装服务,例如超时以及根据结果分派成功和失败操作.

waitForFetch is an action that invokes the fetch function passed in to it (as provided by FileService). It basically provides wrapper services to the fetch, like timeout and dispatching success and failure actions depending on the outcome.

该组件从不知道 API 结果(尽管它可能会启动它),它只是等待数据出现在存储中.

The component never knows about the API result (although it may initiate it), it just waits on data to appear in the store.

至于仅在组件中调用 API 的缺点,这取决于可测试性、应用程序复杂性.和团队规模.

As for drawback of just calling the API in the component, it depends on testability, app complexity. and team size.

  • 可测试性 - 可以在单元测试中模拟服务.
  • 应用复杂性 - 可以处理与 API 调用正交的超时/成功/失败.
  • 团队规模 - 更大的团队,将任务分成更小的部分.

这篇关于Vue - API 调用是否属于 Vuex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆