【问题标题】:Form submission before route leave in vue jsVue js中路由离开前的表单提交
【发布时间】:2020-05-23 15:57:22
【问题描述】:

我是 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);
}

谢谢。

【问题讨论】:

标签: javascript vue.js vue-router


【解决方案1】:

编辑评论

你需要注意这些:

  1. PromisifyhandleArticleSubmit 方法
  2. 使 beforeRouteLeave 异步
  3. 使用try/cache来检查promise,所以如果被拒绝(表单有错误)页面不会改变,如果你也可以记录错误想要。

在下面看看它是如何实现的:


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

旧评论

这在 Vue Router 文档中的 Navigation Guards 作为 Leave Guard 中特别提到。

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

或者如果你有一个自定义的模态系统,让它异步,并确保你的模态返回一个承诺:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多