elementUI表单校验动态添加校验规则

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了elementUI表单校验动态添加校验规则脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
elementui动态添加校验规则,场景:
如果活动名称为空,则所有字段非必填
如果活动名称不为空,则具体活动名称提示必填
 
<template>
  <div id="app">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="活动名称" PRop="name">
        <el-input v-model="form.name" @blur="blur()"></el-input>
      </el-form-ITem>
      <el-form-item label="具体活动" prop="name1">
        <el-input v-model="form.name1"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "app",
  components: {},
  data() {
    return {
      form: {
        name: "",
        name1: "",
      },
      rules: {},
    };
  },
  methods: {
    addRules() {
      // 定义规则
      const newRules = [{ required: true, trigger: "change", message: "具体活动必填" }];
      // 给rules对象添加规则
      this.rules = { ...this.rules, name1: newRules };
    },
    removeRules() {
        // 清除指定校验规则
        this.$refs.form.clearValidate(["name1"]);
      // 这行必须
      this.rules = { ...this.rules, name1: [] };
    },

    blur() {
      if (this.form.name === "") {
        this.removeRules();
      } else {
        this.addRules();
      }
    },
  },
};
</script>

  效果:

活动名称为空时,具体活动选项非必填

elementUI表单校验动态添加校验规则

 

 

 

 

活动名称不为空时,具体活动选项必填

elementUI表单校验动态添加校验规则

 

 

脚本宝典总结

以上是脚本宝典为你收集整理的elementUI表单校验动态添加校验规则全部内容,希望文章能够帮你解决elementUI表单校验动态添加校验规则所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。