Vue如何查看表单中的所有字段是否已填写

How to see if all fields are filled in a form with Vue

我在 <template> 标签之间有一个表单

<form>
<div class="form-group">
  <label for="email">Email address</label>
  <input v-model="email" for="email" type="email" class="form-control" placeholder="Enter email" required>
</div>
<div class="form-group">
  <label for="name">Name</label>
  <input v-model="name" for="name" type="text" class="form-control" placeholder="Name" required>
</div>
<div class="form-group">
  <label for="password">Password</label>
  <input v-model="password" type="password" class="form-control" for="password" placeholder="Password" required>
</div>
<div class="form-group">
  <label for="Confirm">Confirm Password</label>
  <input v-model="confirmPassword" type="password" class="form-control" for="Confirm" placeholder="Confirm Password" required>
</div>
<div class="form-group form-check">
  <input type="checkbox" class="form-check-input" id="exampleCheck1" required>
  <label class="form-check-label" for="exampleCheck1">I agree to the terms and conditions</label>
</div>
<button v-on:click="Submit" type="submit" class="btn btn-primary">Submit</button>

我有 v-model,它正在实时更新 script 部分中的 data

data:

data(){
return{
  email: undefined,
  password: undefined,
  confirmPassword: undefined,
  name: undefined
}

},

我预计 undefined 会在 v-model

之前更新

单击表单按钮时,将调用 Submit 方法。

Submit方法:

如果输入为 empty 则打印为空,如果输入不为空则为 passed(按预期工作)

如果输入为空,则打印 empty,即使两个输入都已填充,也会打印 empty(与预期不同)

methods:{
Submit(){

  console.log(this.email); //prints the data in entered in the form correctly
  console.log(this.name);  //prints the data in entered in the form correctly
  console.log(this.password); //prints the data in entered in the form correctly
  console.log(this.confirmPassword); //prints the data in entered in the form correctly

  if(this.email == undefined){ console.log('Empty')} //prints empty if input is `empty` and `passed` if the input is not empty (works as expected)
  else{console.log('passed')};


  if(this.email || this.name == undefined){console.log('Empty');} //prints `empty` if input is empty and `empty` even if both the inputs are filled (not as expected) 
  else {console.log('Passed');}
  
 }
}

如果至少有一个操作数为真,OR || operator 将 return 为真。

在您的第二个 if 语句中,它检查 this.email 是否为真值,或者 this.name 是否为 undefined,那么它将 return 为真。在你的场景中,如果两个值都被填充,那么它就是真的。

您想使用 AND && operator 检查两个条件是否为真。

或者,对于 vue,您可以使用像 Vuelidate or VeeValidate.

这样的验证库