具体用法:
先写一个很简单的form:
<template>
<div>
<!-- model定义表单绑定的数据 -->
<el-form
:model="data">
<el-form-item>
<el-input v-model="data.name">
</el-input>
</el-form-item>
<el-form-item>
<el-select v-model="data.books">
<el-option
v-for="book in books"
:key="book.value"
:label="book.label"
:value="book.value">
</el-option>
</el-select>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { ref } from 'vue'
export default{
setup(){
const data = ref(
{
name:"小明",
books:""
}
)
const books = ref([
{
label:"c++高级程序设计",
value:"c"
},
{
label:"java从入门到放弃",
value:"java"
}
])
return{
data,
books
}
}
}
</script>
<style scoped>
.example-block {
margin: 1rem;
}
.example-demonstration {
margin: 1rem;
}
</style>
自定义验证规则方法:
1 在form表单上添加rules
2 在form-item上添加prop,后面根据prop定位rule应用在哪条:
3 写验证函数
4 把验证函数和验证规则绑定:
这里把checkBooks规则绑定给books,books对应的是上面定义的prop
过程中踩的坑:
1 注意prop添加的位置:prop是添加到form-item上,一开始加错了,绑定rules没有生效
2 rules的trigger,设置验证规则触发方式,change是对应字段要发生改变的时候即判断规则,blur为失去焦点的时候验证,blur用于Input,change用于其他的,对于别的表单行,不要写blur,会不起效
整体代码:
<template>
<div>
<!-- model定义表单绑定的数据 -->
<el-form
:model="data"
:rules="rules">
<el-form-item label="姓名" prop="name">
<el-input v-model="data.name" >
</el-input>
</el-form-item>
<el-form-item label="书籍" prop="books">
<el-select v-model="data.books" >
<el-option
v-for="book in books"
:key="book.value"
:label="book.label"
:value="book.value">
</el-option>
</el-select>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { ref,reactive } from 'vue'
export default{
setup(){
const data = ref(
{
name:"小明",
books:""
}
)
const books = ref([
{
label:"c++高级程序设计",
value:"c"
},
{
label:"java从入门到放弃",
value:"java"
}
])
const checkBooks = (rule,value,callback)=>{
//value为当前行绑定的vlue
console.log(value )
if(value ){
callback(new Error('test'))
}
else{
callback(new Error('请选择书本'))
}
}
const checkName = (rule,value,callback) => {
callback(new Error('blur'))
}
const rules = reactive(
{
name: [ { required: true , validator:checkName, trigger: 'blur' } ],
books: [ { required:true, validator:checkBooks,trigger:'change' } ]
}
)
return{
rules,
data,
books,
}
}
}
</script>
<style scoped>
.example-block {
margin: 1rem;
}
.example-demonstration {
margin: 1rem;
}
</style>