Как сделать выполнение условия по статусу запроса?
Есть кастомный notification который срабатывает на submit. Но проблема в том, что он выдает диалоговое окно вне зависимости от того прошел запрос валидацию или нет. Хочу сделать условие через код статуса самого запроса, но не понимаю как к нему обратиться.
вот сам Vue компонент
<template>
<div>
<notifications classes="notification-edit" group="foo" />
<form @submit.prevent="submit">
<div class="form-group">
<label for="task-title">Task name</label>
<input v-model="task.title"
type="text"
name="title"
class="form-control"
id="task-title">
<div class="text-danger pt-1" v-show="errors.title">{{errors.title}}</div>
</div>
<div class="form-group">
<label for="task-description">Task description</label>
<textarea name="description"
class="form-control"
id="task-description"
rows="3"
v-model="task.description"></textarea>
<div class="text-danger pt-1" v-show="errors.description">{{errors.description}}</div>
</div>
<button type="submit" class="btn btn-success">Update task</button>
</form>
</div>
</template>
<script>
export default {
props: [
'oldtask'
],
data() {
return {
task: {
id: '',
title: '',
description: ''
},
errors: {
title: '',
description: ''
},
}
},
mounted() {
this.getDate();
},
methods: {
getDate() {
this.task = this.oldtask;
},
submit() {
this.errors.title = ''
this.errors.description = ''
axios
.patch(`/api/tasks/`+this.task.id, {
id: this.oldtask.id,
title: this.task.title,
description: this.task.description
})
.then(response => {
window.location.href = `/`;
})
.catch(error => {
if (error.response.status === 422) {
console.log(error.response.data.errors);
this.errors.title = error.response.data.errors.title[0]
this.errors.description = error.response.data.errors.description[0]
}
})
//кастомный notification
this.$notify({
group: 'foo',
title: 'Hello user!',
text: 'Ты отредактировал таску!'
})
},
},
}
</script>
Ответы (1 шт):
Автор решения: Жека Диулин
→ Ссылка
Так ведь у тебя this.$notify() вызывается за пределами хуков then и catch промиса! То есть уведомление всплывает даже раньше, чем сервер ответит. Чтобы это исправить, помести вызов this.$notify() в обработчик нужного тебе хука:
axios.patch(`/api/tasks/`+this.task.id, {
id: this.oldtask.id,
title: this.task.title,
description: this.task.description
})
.then(response => {
// Вставить this.$notify() сюда
})
.catch(error => {
// И/или сюда
})