0

尝试使用 Vue Validate 在引导表单(b-form)中进行验证提交表单时滚动到第一个错误

4

1 回答 1

1

我想你正在寻找这样的东西-

const app = new Vue({
  el:'#app',
  data:{
    errors:[],
    name:null,
    age:null,
    movie:null
  },
  methods:{
    checkForm:function(e) {
      this.$refs.errorP.scrollIntoView();
      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();
      
    }
  }
})
input,select {
  margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" @submit="checkForm" action="/something" method="post">
  <div ref="errorP">
  <p v-if="errors.length" >
    <b>Please correct the following error(s):</b>
    <ul>
      <li v-for="error in errors">{{ error }}</li>
    </ul>
  </p>
  </div>
  <div style="height: 1000px;">
  Scroll to the bottom to see the form
  </div>
  <p>
    <label for="name">Name<label>
    <input type="text" name="name" id="name" v-model="name">
  </p>

  <p>
    <label for="age">Age<label>
    <input type="number" name="age" id="age" v-model="age" min="0">
  </p>

  <p>
    <label for="movie">Favorite Movie<label>
    <select name="movie" id="movie" v-model="movie">
      <option>Star Wars</option>
      <option>Vanilla Sky</option>
      <option>Atomic Blonde</option>
    </select>
  </p>

  <p>
    <input type="submit" value="Submit">  
  </p>

</form>

https://jsfiddle.net/anupdg/j24xt7rd/1/

于 2020-03-12T09:42:48.040 回答