As a newcomer to VueJs, I am facing a problem with creating a form. My goal is to display an alert dialog with the message "you might lose the data, please save the data before you leave," and upon clicking 'yes', the form should be submitted and the route should change.
I understand that this can be achieved using beforeRouteLeave(to, from, next)
, but how can I submit the form before leaving the route when clicking 'yes' in the alert box?
https://i.sstatic.net/rw1f1.png
In the image above, my current route is /create
.
handleArticleSubmit() {
// Collect form data
let formData = new FormData();
// Start Button Loading
this.isSubmittingArticle = true;
axios
.post("/articles", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(res => {
// Stop button loading
this.isSubmittingArticle = false;
// Show alert message
this.snackbar = {
isVisible: true,
color: "success",
text: "Article submitted successfully"
};
})
.catch(error => {
// Stop button loading
this.isSubmittingArticle = false;
// Show alert
// Show alert message
this.snackbar = {
isVisible: true,
color: "error",
text: error
};
}
});
}
},
The code mentioned above saves the article, and I aim to change the route only if the form submits with all validations (such as blank fields or numbers). If not, the route should not change. Thank you for your help.
beforeRouteLeave(to, from, next) {
const answer = window.confirm(
"You might lose the data, please save it before leaving."
);
if (answer) {
this.handleArticleSaveDraft();
next();
} else {
next(false);
}
Thank you.