发布于 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)
})
}
}
发布于 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
FormData
POSTing例如图像文件
列表可能会变得很长。所有这些都不属于组件,因为它与视图无关。视图只需要结果数据或错误消息。
这也意味着你可以独立测试你的组件和api。
https://stackoverflow.com/questions/45839198
复制相似问题