0

尝试在包含简单 html 表单的页面上设置基本的“您确定要离开此页面”类型提示。

形式:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div id="app">
      <form id="webform" action='#' method='POST' @submit.prevent="doSubmit()">
        <input v-validate="'required'" :class="{'input': true, 'is-danger': errors.has('cust_name_first') }" name="cust_name_first" type="text">
        <span v-show="errors.has('cust_name_first')" class="help is-danger">{{ errors.first('cust_name_first') }}</span>
      </form>
    </div>
    <!-- div id app -->
  </body>
</html>

和javascript:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vee-validate/2.0.9/vee-validate.min.js"></script>
    <script>
        formsubmitval = 1;
        Vue.use(VeeValidate);
        new Vue({
            el: "#app",
            template: '#app',
            data() {
                return {
                    cust_name_first: null,
                    cust_id: null,
                    sales_name_first: null,
                };
            },
            methods: {
                doSubmit() {
                    this.$validator.validateAll().then(function(result){
                        if (!result){
                            //this means a validation failed, so exit without doing anything
                            return;
                        }
                        //here you would put your form submit stuff
                        formsubmitval=0;
                        document.getElementById('webform').submit();
                    });
                }
            }
        });
        if (formsubmitval==1)
        {
            window.onbeforeunload = function(e) {
                e = e || window.event;
                e.preventDefault = true;
                e.cancelBubble = true;
                e.returnValue = 'test';
            }
        }           
    </script>

问题是没有提示我离开页面,并且任何用户输入的数据都丢失了。我对上面的脚本做错了什么?

4

1 回答 1

0

我让这变得比它需要的更困难。只需添加 onbeforeunload 事件,然后在提交时将其设置为 null。工作一种享受。

更新的javascript:

<script>
    window.onbeforeunload = function() {
        return true;
    };
    Vue.use(VeeValidate);
    new Vue({
        el: "#app",
        template: '#app',
        data() {
            return {
                cust_name_first: null,
                cust_id: null,
                sales_name_first: null,
            };
        },
        methods: {
            doSubmit() {
                this.$validator.validateAll().then(function(result){
                    if (!result){
                        //this means a validation failed, so exit without doing anything
                        return;
                    }
                    //here you would put your form submit stuff
                    window.onbeforeunload = null;
                    document.getElementById('webform').submit();
                });
            }
        }
    });

</script>
于 2018-07-02T19:38:02.440 回答