Vue - API调用属于Vuex吗?

Pet*_*sko 2 vue.js axios vuex

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

问题是关于最好的实践.API调用是否属于Vuex操作?这种方法有利有弊吗?

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

Ric*_*sen 6

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

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

FileService .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) )
  },
}
Run Code Online (Sandbox Code Playgroud)

我在下面的另一个服务中使用它(层数取决于你).
注意,外部服务正在检查商店以查看是否已经发生了提取.

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
  }
},
Run Code Online (Sandbox Code Playgroud)

waitForFetch是一个调用传递给它的fetch函数的动作(由FileService提供).它基本上为提取提供包装服务,如超时和调度成功和失败操作,具体取决于结果.

组件永远不会知道API结果(尽管它可能会启动它),它只是等待数据出现在商店中.


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

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