html
<div id="app" v-cloak>
<p v-for="(item, index) in errors" :key="item"><span v-if="index == 0">{{item}}</span></p>
<label for="">
<input type="text" value="" v-model="name">
姓名
</label>
<label for="">
<input type="text" value="" v-model="age">
年龄
</label>
<label for="">
<input type="text" value="" v-model="sex">
性别
</label>
<button @click="checkForm">提交</button>
</div>
css
[v-cloak]{
display: none;
}
#app{
margin-top: 300px;
}
label{
display: block;
margin-top: 20px;
margin-left: 400px;
}
button,
p{
margin-top: 20px;
margin-left: 400px;
}
js
const app = new Vue({
el:'#app',
data:{
errors:[],
name:null,
age:null,
sex:null
},
methods:{
checkForm:function() {
this.errors = [];
if(this.name && this.age && this.sex) {
confirm('提交成功')
return true;
};
if (!this.name) this.errors.push('请输入用户名~')
if (!this.age) this.errors.push('请输入年龄~')
if (!this.sex) this.errors.push('请输入性别~')
}
}
})
非常短小精悍。我们定义了一个数组来放置错误,并将这三个表单字段的默认值设为 null。