Is there a way to efficiently reuse the same Vue-component for both editing and creating new users?
While working with vue-router
, I have implemented a beforeRouteEnter
method to fetch data via API. Depending on whether an ID
is set in the URL parameter, I determine if it's for updating an existing user (edit
) or creating a new one.
This is my current approach:
beforeRouteEnter (to, _from, next) {
if (to.params.id) {
axios
.all ([
axios.get ('/api/user/' + to.params.id),
axios.get ('/api/states/users')
]).then (axios.spread ((userRes, statesRes) => {
next ((vm) => {
vm.user = userRes.data.data;
vm.states = statesRes.data.data;
vm.create = false;
});
})
);
}
else {
axios
.all ([
axios.get ('/api/states/users')
]).then (axios.spread ((statesRes) => {
next ((vm) => {
vm.states = statesRes.data.data;
});
})
);
}
},
I acknowledge that this implementation may not be the most elegant solution. One idea I had was to store the URL in an array and push '/api/user/' + to.params.id)
to that array when to.params.id
is not empty. However, I am unsure about how to handle the axios.spread
part in this scenario.
Therefore, my question remains: How can I optimize my code for better performance and readability?