对话框的表单校验——模板笔记

目的:

减少重复工作、简化开发速度

案例:

1.设置一个对话框:

<el-dialog
    width="50%"
    top="60px"
    :title='dialogTitle'
    :visible.sync="dialogVisible"
    :show-close="false"
    :append-to-body="false"
    :close-on-click-modal='false'
    :lock-scroll="false"
>
    <DialogForm
        v-if="newOrEdit"
        :form-info="ruleForm"
        @form-change="formChange"/>
    <aceEditor
        v-if="seeAceEditor"
        :read-only="true"
        :show-content="showJson"
        :options="options"
        style="margin-top: -30px"
    />
</el-dialog>

computed: {
    formInfo () {
      return {
        type: this.formType,
        repeatName: [],
        form: this.ruleForm
      }
    },
    newOrEdit () {
      return this.dialogTitle === '新建' || this.dialogTitle === '编辑'
    },
    seeAceEditor () {
      return this.dialogTitle === '查看返回协议' || this.dialogTitle === '查看请求协议'
    }
  }

 

2.抽离表单:

<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
    >
      <el-form-item
        label="特征中文名"
        prop="name">
        <template slot="label">
          <span>
            <span>特征中文名</span>
            <el-tooltip
              content="同一业务下'特征中文名'不可重名"
              placement="bottom"><i class="fa fa-info-circle"/>
            </el-tooltip>
          </span>
        </template>
        <el-input
          v-model="form.name"
          placeholder="请输入特征中文名"/>
      </el-form-item>
      <el-form-item>
        <span class="form-item-submit">
          <el-button
            @click="cancelForm">取消</el-button>
          <el-button
            type="primary"
            :loading="loadSubmit"
            @click="submitForm">确定</el-button>
        </span>
      </el-form-item>
    </el-form>
    <!--嵌套的对话框-->
    <el-dialog
      title="特征模板列表"
      width="50%"
      top="60px"
      :visible.sync="dialogVisibleNest"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal='false'
      :lock-scroll="false"
    >
      <div>222
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  computed: { // 计算属性
    categoryList () {
      return this.$store.state.getGameList.activityConfig.category_list || []
    }
  },
  props: {// 需要的参数统一传过来
    formInfo: {
      type: Object,
      default () {
        return {
          type: 'new',
          repeatName: [],
          form: {
            name: ''
          }
        }
      }
    }
  },
  data () {
    const validateName = (rule, value, callback) => {
      if (value) {
        const rtx = /^[\u4E00-\u9FA5a-zA-Z0-9_]+$/
        if (!value.match(rtx)) {
          callback(new Error('只允许中英文、数字、下划线'))
        } else if (this.formInfo.repeatName.indexOf(value) !== -1) {
          callback(new Error('该命名已存在'))
        } else {
          callback()
        }
      } else {
        callback(new Error('不能为空'))
      }
    }
    const validateType = (rule, value, callback) => {
      if (value) {
        const rtx = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
        if (!value.match(rtx)) {
          callback(new Error('字母开头,允许5-16字节,允许字母数字下划线'))
        } else if (this.formInfo.repeatName.indexOf(value) !== -1) {
          callback(new Error('该命名已存在'))
        } else {
          callback()
        }
      } else {
        callback(new Error('不能为空'))
      }
    }
    // const validatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('不可为空'))
    //   } else {
    //     let result = this.removeStrNotes(value) // 去除注释
    //     if (typeof result === 'string') {
    //       try {
    //         let obj = JSON.parse(result) // 转换成json对象
    //         if (typeof obj === 'object' && obj) {
    //           callback()
    //         } else {
    //           callback(new Error('json格式有误'))
    //         }
    //       } catch (e) {
    //         callback(new Error(e))
    //       }
    //     } else {
    //       callback(new Error('json格式有误'))
    //     }
    //   }
    // }
    return {
      form: {
        name: '',
        type: '',
        user: '',
        checked: 0
      },
      rules: {
        name: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        type: [
          { required: true, validator: validateType, trigger: 'blur' }
        ],
        checked: [
          { required: true, message: '请选择是否使用模板', trigger: 'change' }
        ],
        user: [// 多选是数组
          { required: false, type: 'array', message: '请输入关键字,匹配特征关系人,可多选', trigger: 'change' }
        ]
      },
      dialogVisibleNest: false, // 查看嵌套的对话框
      loadSubmit: false // 提交
    }
  },
  watch: {
    'formInfo': {
      immediate: true,
      handler (val) { // 初始化
        console.log(val, '初始化')
        if (val.type === 'new') {
          this.repeatName = val.repeatName
          this.form = {
            name: '',
          }
        } else if (val.type === 'edit') {
          this.repeatName = []
          this.form = val.form
        }
        this.$nextTick(function () {
          // this.$refs['ruleForm'].resetFields()// 清空表单内容
          this.$refs['ruleForm'].clearValidate()// 清空报错
          this.$refs['inputFocus'].$el.querySelector('input').focus()
        })
      }
    }
  },
  methods: {
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$emit('form-change', this.form, this.formInfo.type)// 回调:成功提交
        }
      })
    },
    cancelForm () {
      this.$emit('form-change')// 回调:关闭对话框
      this.$refs['ruleForm'].resetFields()// 清空表单内容
      this.$refs['ruleForm'].clearValidate()// 清空报错
    }
  }
}
</script>
<!-- 不校验去除低栏边距 -->
<style scoped>
.form-item-bottom{
  margin-bottom: 0;
}
.form-item-submit{
  margin-top: 20px;
  float: right
}
</style>

 

未完待续...

转载于:https://www.cnblogs.com/wheatCatcher/p/11453423.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值