在本文中,它说:
虽然这通常很糟糕,但您可以直接在组件中使用Axios从方法,生命周期挂钩或任何时候获取数据.
我想知道为什么?我经常使用生命周期钩子来获取数据(特别是来自created()).我们应该在哪里写请求电话?
Sri*_*mam 18
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)
})
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当您需要获取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
}
Run Code Online (Sandbox Code Playgroud)
所以你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)
})
}
}
Run Code Online (Sandbox Code Playgroud)
这对于小型应用程序或小部件来说很好,但在真正的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
})
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,您的"无axios"代码实际上并不短得多,但想象一下您可能会保留的组件:
FormData用于POST的例如图像文件列表可以变长.所有这些都不属于组件,因为它与视图无关.视图仅需要生成的数据或错误消息.
这也意味着您可以独立测试组件和api.
| 归档时间: |
|
| 查看次数: |
4731 次 |
| 最近记录: |