In this article,上面写着:
虽然这通常是一种糟糕的做法,但您可以在组件中直接使用Axios从方法、生命周期挂钩或任何时候获取数据.
我想知道为什么?我通常使用很多生命周期挂钩来获取数据(尤其是从created()
个).我们应该在哪里写请求电话?
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)
})
}
}