我是VueJs的新手,我陷入了一个问题。我正在创建一个表单,并希望显示一个警告对话框,并显示消息“您可能会丢失数据,请在离开之前保存数据”。当我单击“是”时,应提交表格并更改路线。
我知道我们可以使用beforeRouteLeave(to, from, next)
来做到这一点,但是如何在警报提示框中单击“是”之前提交表单?
/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 submited successfully"
};
})
.catch(error => {
// Stop button loading
this.isSubmittingArticle = false;
// Show alert
// Show alert message
this.snackbar = {
isVisible: true,
color: "error",
text: error
};
}
});
}
},
以上提到的代码保存了我想更改路线的文章,如果表单提交了所有验证验证(如空白,数字等),则不应该更改路线。 谢谢 现在我正在使用此代码来更改路线:
beforeRouteLeave(to, from, next) {
const answer = window.confirm(
"you might lose the data, please save the data before you leave."
);
if (answer) {
this.handleArticleSaveDraft();
next();
} else {
next(false);
}
谢谢。
答案 0 :(得分:1)
您需要注意以下事项:
在下面查看其实现方式:
methods: {
handleArticleSubmit() {
return new Promise((resolve, reject) => { // 1. Promisify the method
let formData = new FormData()
this.isSubmittingArticle = true
axios
.post("/articles", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(res => {
this.isSubmittingArticle = false
this.snackbar = {
isVisible: true,
color: "success",
text: "Article submited successfully"
}
resolve() // Resolve the promise (all is good)
})
.catch(error => {
this.isSubmittingArticle = false
this.snackbar = { // Show alert message
isVisible: true,
color: "error",
text: error
}
reject(error) // Reject it when error happens
})
})
}
},
async beforeRouteLeave (to, from, next) { // 2. Make this async
let answer = window.confirm("you might lose the data, please save the data before you leave.")
if (answer) {
// 3. Try/catch to confirm the resolve
try{
await this.handleArticleSubmit()
// Resolved
next()
} catch (err) { // Rejected
next(false)
log(err)
}
} else {
next(false)
}
}
在Navigation Guards中,Vue Router文档中将其特别称为“离开守卫”。
beforeRouteLeave (to, from, next) {
const answer = window.confirm('you might lose the data, please save the data before you leave.')
if (answer) {
this.submit() // Submit your form here however you want
next()
} else {
next(false)
}
}
或者,如果您有一个自定义模态系统,请使其异步,并确保您的模态返回一个promise:
async beforeRouteLeave (to, from, next) {
const answer = await this.openModal()
if (answer) {
this.submit() // Submit your form here however you want
next()
} else {
next(false)
}
}