使用@submit="onSubmit"提交,然后button按钮native-type="submit"提交,单个form的时候没有问题,但是多个form组件多次点击的时候就容易出现混乱提交
javascript
<van-form @submit="onSubmit">
<van-field
v-model="username"
name="用户名"
label="用户名"
placeholder="用户名"
:rules="[{ required: true, message: '请填写用户名' }]"
/>
<van-field
v-model="password"
type="password"
name="密码"
label="密码"
placeholder="密码"
:rules="[{ required: true, message: '请填写密码' }]"
/>
<div style="margin: 16px;">
<van-button round block type="info" native-type="submit">提交</van-button>
</div>
</van-form>
优化使用@click方法点击,然后validate()进行校验***********************************
javascript
<van-form ref="ruleForm">
<van-field
v-model="submitForm.username"
name="用户名"
label="用户名"
placeholder="用户名"
:rules="rules.username"
/>
<van-field
v-model="submitForm.password"
type="password"
name="密码"
label="密码"
placeholder="密码"
:rules="rules.password"
/>
<div style="margin: 16px;">
<van-button round block type="info" @click="handleSubmit">提交</van-button>
</div>
</van-form>
<script>
export default {
data(){
submitForm:{
username:"",
password:"",
},
rules:{
username:[{ required: true, message: '请填写用户名' }],
password:[{ required: true, message: '请填写密码' }]
}
},
methods:{
handleSubmit(){
const _this = this;
this.$refs.submitForm.
?.validate()
.then(() => {
console.log("验证成功");
//提交数据 _this.submitForm
console.log(_this.submitForm)
})
.catch(() => {
console.log("验证失败");
});
}
}
}
</script>