如何查看是否所有字段都用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,它正在实时更新data部分中的script

data

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

},

我希望undefinedv-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');}
  
 }
}

解决方法

如果至少一个操作数为true,则OR || operator将返回true。

在第二个if语句中,它检查this.email是否为真值,或者this.nameundefined,则返回true。在您的方案中,如果两个值都被填满,那么它将完全成立。

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

或者,对于vue,您可以使用VuelidateVeeValidate之类的验证库。