首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么在组件中使用Axios或HTTP调用被认为是不好的做法?

为什么在组件中使用Axios或HTTP调用被认为是不好的做法?
EN

Stack Overflow用户
提问于 2017-08-23 20:03:08
回答 2查看 5.6K关注 0票数 18

In this article,它说:

虽然这通常是一种糟糕的实践,但您可以直接在组件中使用Axios从方法、生命周期挂钩或任何时候获取数据。

我想知道为什么?我们应该在哪里编写请求调用?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-23 22:01:22

直接在组件中编写API方法会增加代码行数并使其难以阅读。据我所知,author建议将API方法分离到一个Service中。

让我们以必须获取top posts并对数据进行操作的情况为例。如果你在组件中这样做,它是不可重用的,你必须在你想要使用它的其他组件中复制它。

export default {
  data: () => ({
    top: [],
    errors: []
  }),

  // Fetches posts when the component is created.
  created() {
    axios.get(`http://jsonplaceholder.typicode.com/posts/top`)
    .then(response => {
      // flattening the response
      this.top = response.data.map(item => {
         title: item.title,
         timestamp: item.timestamp,
         author: item.author
      })
    })
    .catch(e => {
      this.errors.push(e)
    })

  }
}

因此,当您需要在另一个组件中获取top post时,您必须复制代码。

现在让我们将API methods放在一个Service中。

api.js file

const fetchTopPosts = function() {
  return axios.get(`http://jsonplaceholder.typicode.com/posts/top`)
        .then(response => {
          // flattening the response
          this.top = response.data.map(item => {
             title: item.title,
             timestamp: item.timestamp,
             author: item.author
          })
        }) // you can also make a chain.
}

export default {
   fetchTopPosts: fetchTopPosts
}

因此,您可以在您希望的任何组件中使用上面的API methods

在此之后:

import API from 'path_to_api.js_file'
export default {
      data: () => ({
        top: [],
        errors: []
      }),

      // Fetches posts when the component is created.
      created() {
         API.fetchTopPosts().then(top => {
            this.top = top
         })
         .catch(e => {
          this.errors.push(e)
         })

      }
    }
票数 18
EN

Stack Overflow用户

发布于 2017-08-23 21:57:55

它对于小型应用程序或小部件很好,但在真正的SPA中,最好将API抽象到它自己的模块中,如果您使用vuex,则使用操作来调用该api模块。

您的组件不应该关心它的数据是如何以及从哪里来的。该组件负责UI,而不是AJAX。

import api from './api.js'

created() {
  api.getUsers().then( users => {
    this.users = users
  })
}

// vs.

created() {
  axios.get('/users').then({ data }=> {
    this.users = data
  })
}

在上面的示例中,您的"axios-free“代码并不是很短,但是可以想象一下,您可以在组件中保留什么:

为符合您的component

  • header配置(内容类型、访问令牌...)的服务器创建
  • 处理HTTP错误,例如来自服务器的数据创建
  • FormData

POSTing例如图像文件

列表可能会变得很长。所有这些都不属于组件,因为它与视图无关。视图只需要结果数据或错误消息。

这也意味着你可以独立测试你的组件和api。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45839198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档