el-form-item设置动态rules
时间: 2023-12-14 09:30:00 浏览: 102
el-form-item组件的rules属性用于设置字段的校验规则。如果需要根据某种条件动态设置rules,可以使用计算属性来实现。以下是一个示例:
```html
<template>
<el-form :model="form">
<el-form-item label="用户名" prop="username" :rules="usernameRules">
<el-input v-model="form.username"></el-input>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {
username: ''
}
};
},
computed: {
usernameRules() {
const rules = [];
if (this.form.username) {
rules.push({
required: true,
message: '用户名不能为空',
trigger: 'blur'
});
// 添加其他规则...
}
return rules;
}
}
};
</script>
```
在上述示例中,我们定义了一个计算属性`usernameRules`,根据`form.username`的值动态生成rules。当`form.username`有值时,会添加required规则,否则不添加任何规则。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)