In this article,上面写着:

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

我想知道为什么?我通常使用很多生命周期挂钩来获取数据(尤其是从created()个).我们应该在哪里写请求电话?

推荐答案

直接在组件中编写API个方法会增加代码行数,并使阅读变得困难.

让我们举一个例子,你必须取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)
         })

      }
    }

Vue.js相关问答推荐

如何只提取一次用于无线电组过滤的数据,而不是针对数据库中的每个条目提取数据?

如何使用composition api v-model Select 框获取其他JSON 值?

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

在 v-for 中定义变量有什么问题吗?

Vue Js Composition Api 未定义(读取名称)

Defer推迟执行,直到外部脚本加载到 Vue.js

Vue 和 Bootstrap Vue - 动态使用插槽

Vue3在'vue-router'中找不到导出'createWebHistory,createRouter'

使用 Vue.js (cdn) 在特定元素上切换显示/隐藏

等待来自 WDS 的更新信号

NUXT如何将数据从页面传递到布局

在Vue中单击路由链接上的激活方法

使计算的 Vue 属性依赖于当前时间?

更改时(change)调用函数

在 Vue.js 模板中调用函数

如何从扩展面板(Vuetify)中删除阴影?

Vue.js 和 jQuery datepicker/timepicker 双向绑定

返回 VueJS 方法的Native Code消息

Vue 3 组合 API 数据()函数

Vuex 模块Mutations