Answer the question
In order to leave comments, you need to log in
Why do Vue put requests in services?
Why do many people in vue js put requests in services, and then call the request in vuex actions, when you can just write it in actions?
We have vue.js, we have vuex. I began to notice that many make requests to the services directory .
For example, there is a User service:
import api from '../api' // Там axios
class UserService {
async getById (id) {
return await api.get('/user/', {
params: {
id
}
})
}
// Другие запросы с работой пользователя
}
export default UserService
import UserService from '../services/UserService'
//...
export const actions = {
async getUserById ({ commit }, id) {
const { data } = await UserService.getById(id)
commit('setUser', data)
},
}
//...
Answer the question
In order to leave comments, you need to log in
axios.get(ENDPOINT + '/api/' + API_METHOD, {
params: {
id
}
})
.catch
...
getUser(id)
. It contains all the logic for working with a request, determining API routes, error handling, and so on. Only one function and parameter sticks out.Business logic should not be in components. And this is not even a specific case in VueJS, but in general, in general. They do the same in both Angular and React. The component should not know how the data is loaded specifically.
I will add to everything already listed - it is very convenient for testing . You can mock modules/methods and don't bother testing the real API.
I haven't worked with Vue.js, but it's very similar to the Redux implementation - separating application state, application view, and requests. In order not to directly change the state of the application, additional layers are created. Actions in this case is not only a request, but also a state change, and the same requests in theory can be used in different actions, which is why they are separated.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question