【问题标题】:How to prevent a form to navigate to next step. while input fields is empty. Using vue.js如何防止表单导航到下一步。而输入字段为空。使用 vue.js
【发布时间】:2021-03-19 17:06:46
【问题描述】:

在这里,我试图阻止表单在输入字段为空时导航到下一步。我已经在 vue 中为此编写了一个方法但是我无法实现这一点,因为我是 vue.js 的新手。所以我正在努力实现,但我失败了。因此,如果有人有任何想法,请帮助我。我想在字段为空并且用户单击下一步时突出显示边框,然后字段边框应突出显示。

<div id="vk_app">
  <form>
  
  <div v-if="step === 1">

    <h1>Step One</h1>
    <p>
    <legend for="name">Your Name:</legend>
    <input id="name" name="name" v-model="category">
    <input id="name" name="name" v-model="password">
    <input id="name" name="name" v-model="Email">
    </p>

    <button @click.prevent="next()">Next</button>

  </div>
  <div v-if="step === 2">
      <template>
       <input id="name" name="name" v-model="address">
        <input id="name" name="name" v-model="h_no">
        <input id="name" name="name" v-model="mobile">
        <button @click.prevent="prev()">Previous</button>
        <button @click.prevent="next()">Next</button>
      </template>
  </div>

  <div v-if="step === 3">
    <template>
       <input id="name" name="name" v-model="subject">
        <input id="name" name="name" v-model="occupation">
        <button @click.prevent="prev()">Previous</button>
        <button @click.prevent="next()">Next</button>
      </template>

    <button @click.prevent="prev()">Previous</button>
    <button @click.prevent="submit()">Save</button>

  </div>
  </form>
</div>

vue.js

<script>
const app = new Vue({
  el:'#vk_app',
  data() {
    return {
      step:1,
        category:null,
        street:null,
        city:null,
        state:null,
    }
  },
  methods:{
    prev() {
      this.step--;
    },
    next() {
      this.step++;
    },
    checkForm: function (e) {
      if (this.name && this.age) {
        return true;
      }

      this.errors = [];

      if (!this.name) {
        this.errors.push('Name required.');
      }
      if (!this.age) {
        this.errors.push('Age required.');
      }

      e.preventDefault();
    }
    }
});
</script>

【问题讨论】:

标签: vue.js


【解决方案1】:

您有一个方法checkForm,但您似乎从未调用它。

只需更改您的 nextprev 方法以使用该方法,如下所示:

prev() {
  if(this.checkForm()) {
    this.step--;
  }
},
next() {
  if(this.checkForm()) {
    this.step++;
  }
},

【讨论】:

    猜你喜欢
    • 2013-07-25
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多