#vue.js #vuejs2 #vuex
#vue.js #vuejs2 #vuex
Вопрос:
Извлечение моего компонента с одним файлом:
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
data () {
return {
firstname: this.$store.getters.user.firstName,
lastname: this.$store.getters.user.lastName,
}
},
methods: {
...mapActions([
'updateUserProfile'
]),
// Function called when user click on the "Save changes" btn
onSubmit () {
console.log('Component(Profile)::onSaveChanges() - called');
const userData = {
firstName: this.firstname,
lastName: this.lastname
}
this.updateUserProfile(userData);
}
}
}
</script>
В моем магазине VueX:
Я уже управляю состоянием ЗАГРУЗКИ, которое используется для отображения счетчика загрузки.
Теперь я хотел бы программно отобразить виджет уведомлений с помощью библиотеки toastr: toastr.success("Your profile has been updated");
Куда мне следует поместить этот код? Я полагаю, что не рекомендуется размещать этот код непосредственно в функции updateUserProfile хранилища, а больше в компоненте с одним файлом, где выполняется вызов?
/*
* Action used to fetch user data from backend
*/
updateUserProfile ({commit, state}, userData) {
if (!state.jwtToken) {
return
}
// Inform VueX that we are currently loading something. Loading spinner will be displayed.
commit('SET_IS_LOADING', true);
axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {
console.log('PUT /user/profile', res);
// Store user data in local storage
localStorage.setItem('user', JSON.stringify(res.data.data));
// Set user Data in VueX Auth store
commit('SET_USER_DATA', {
user: res.data.data
});
// Reset is Loading
commit('SET_IS_LOADING', false);
})
.catch(error => {
// Reset isLoading
commit('SET_IS_LOADING', false);
});
}
Ответ №1:
Вы можете вернуть обещание из действия
updateUserProfile ({commit, state}, userData) {
if (!state.jwtToken) {
return
}
// Inform VueX that we are currently loading something. Loading spinner will be displayed.
commit('SET_IS_LOADING', true);
return axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {
console.log('PUT /user/profile', res);
// Store user data in local storage
localStorage.setItem('user', JSON.stringify(res.data.data));
// Set user Data in VueX Auth store
commit('SET_USER_DATA', {
user: res.data.data
});
// Reset is Loading
commit('SET_IS_LOADING', false);
return res.data.data
})
.catch(error => {
// Reset isLoading
commit('SET_IS_LOADING', false);
throw error
});
}
а затем в компоненте Vue:
onSubmit () {
console.log('Component(Profile)::onSaveChanges() - called');
const userData = {
firstName: this.firstname,
lastName: this.lastname
}
this.updateUserProfile(userData)
.then(data => {
toastr.success("Your profile has been updated");
})
.catch(error => {
console.error(error)
})
}
Ответ №2:
Вероятно, вам следует вернуть обещание из вашего действия:
/*
* Action used to fetch user data from backend
*/
updateUserProfile ({commit, state}, userData) {
if (!state.jwtToken) {
throw new Error('unauthenticated')
}
// Inform VueX that we are currently loading something. Loading spinner will be displayed.
commit('SET_IS_LOADING', true);
return axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {
console.log('PUT /user/profile', res);
// Store user data in local storage
localStorage.setItem('user', JSON.stringify(res.data.data));
// Set user Data in VueX Auth store
commit('SET_USER_DATA', {
user: res.data.data
});
// Reset is Loading
commit('SET_IS_LOADING', false);
return res.data.data
})
.catch(error => {
// Reset isLoading
commit('SET_IS_LOADING', false);
throw error
});
}
А затем используйте это обещание в своем компоненте:
onSubmit () {
console.log('Component(Profile)::onSaveChanges() - called');
const userData = {
firstName: this.firstname,
lastName: this.lastname
}
this.updateUserProfile(userData).then(user => {
toastr.success("Your profile has been updated")
}).catch(error => {
toastr.error("Something bad happened")
})
}