学习目标:
学习ElementUI 动态添加表单校验规则学习内容:
<template>
<div id="app">
<el-form v-model='data' inline :rules="rules" ref='form'>
<el-form-item label='审批人' prop='user'>
<el-input v-model='data.user' placeholder='审批人'></el-input>
</el-form-item>
<el-form-item label='活动区域'>
<el-select v-model='data.region' placeholder='活动区域'>
<el-option label='区域1' value='beijing'></el-option>
<el-option label='区域2' value='shanghai'></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type='primary' @click='onSubmit'>查询</el-button>
<el-button type='primary' @click='addRule'>添加校验规则</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
data: {
region: '区域二',
user: 'sam'
},
rules: {
user: [{
required: true,
trigger: 'change',
message: '用户名必须输入'
}]
}
}
},
methods: {
onSubmit() {
console.log(this.data);
},
addRule() {
const userValidator = (rule, value, callback) => {
if (this.data.user.length > 3) {
callback();
} else {
callback(new Error('用户名长度必须大于3个字符'));
}
}
const newRule = [
this.rules.user, {
validator: userValidator,
trigger: 'blur',
}
]
this.rules = Object.assign({},this.rules,{user:newRule})
}
}
}
</script>
<style>
</style>