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

查看:163
本文介绍了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?

推荐答案

我在服务而不是Vuex或组件中进行API调用.基本上,将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),

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) )
  },
}

我在以下另一项服务中使用它(层数由您决定).
请注意,外部服务正在检查存储以查看是否已经进行了获取.

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天全站免登陆