在Vue JS中离开路线之前提交表单

时间:2020-05-23 15:57:22

标签: javascript vue.js vue-router

我是VueJs的新手,我陷入了一个问题。我正在创建一个表单,并希望显示一个警告对话框,并显示消息“您可能会丢失数据,请在离开之前保存数据”。当我单击“是”时,应提交表格并更改路线。

我知道我们可以使用beforeRouteLeave(to, from, next)来做到这一点,但是如何在警报提示框中单击“是”之前提交表单?

enter image description here 在上图中,当

时,我的路线是/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);
}

谢谢。

1 个答案:

答案 0 :(得分:1)

编辑后的评论

您需要注意以下事项:

  1. 承诺 handleArticleSubmit方法
  2. 在路由离开前设置 异步
  3. 使用 try / cache 来检查承诺,因此如果被拒绝(表单有错误)页面没有变化,如果您也可以记录错误想要。

在下面查看其实现方式:


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)
  }
}