vant form表单不触发校验
时间: 2023-11-01 22:08:29 浏览: 223
如果你使用的是 Vant 2.x 版本,可以尝试加上`ref`属性,然后在提交表单的时候手动触发校验,示例代码如下:
```html
<template>
<van-form ref="form">
<van-field v-model="name" name="name" label="用户名" placeholder="请输入用户名" :rules="nameRules"></van-field>
<van-field v-model="password" type="password" name="password" label="密码" placeholder="请输入密码" :rules="passwordRules"></van-field>
<van-button type="primary" @click="submitForm">提交</van-button>
</van-form>
</template>
<script>
export default {
data() {
return {
name: '',
password: '',
nameRules: [
{ required: true, message: '请输入用户名' }
],
passwordRules: [
{ required: true, message: '请输入密码' }
]
}
},
methods: {
submitForm() {
this.$refs.form.validate((valid) => {
if (valid) {
// 校验通过,提交表单
console.log('submit form')
} else {
// 校验不通过
console.log('validate failed')
}
})
}
}
}
</script>
```
如果使用的是 Vant 3.x 版本,可以使用 `validate` 方法自动触发校验,示例代码如下:
```html
<template>
<van-form :model="form" :rules="rules">
<van-field v-model="form.name" name="name" label="用户名" placeholder="请输入用户名"></van-field>
<van-field v-model="form.password" type="password" name="password" label="密码" placeholder="请输入密码"></van-field>
<van-button type="primary" @click="submitForm">提交</van-button>
</van-form>
</template>
<script>
export default {
data() {
return {
form: {
name: '',
password: ''
},
rules: {
name: [
{ required: true, message: '请输入用户名' }
],
password: [
{ required: true, message: '请输入密码' }
]
}
}
},
methods: {
submitForm() {
this.$refs.form.validate((valid) => {
if (valid) {
// 校验通过,提交表单
console.log('submit form')
} else {
// 校验不通过
console.log('validate failed')
}
})
}
}
}
</script>
```
其中 `:model` 绑定表单数据,`:rules` 绑定校验规则,点击提交按钮时通过 `validate` 方法触发校验。
阅读全文