关于element-ui:自定义组件如何通过ElementUI-Form校验

43次阅读

共计 1359 个字符,预计需要花费 4 分钟才能阅读完成。

混入 emitter

import emitter from ‘element-ui/src/mixins/emitter’

FormItem

FormItem 存在以下办法

  validate(trigger, callback = noop) {
        this.validateDisabled = false;
        const rules = this.getFilteredRule(trigger);
        if ((!rules || rules.length === 0) && this.required === undefined) {callback();
          return true;
        }

        this.validateState = 'validating';

        const descriptor = {};
        if (rules && rules.length > 0) {
          rules.forEach(rule => {delete rule.trigger;});
        }
        descriptor[this.prop] = rules;

        const validator = new AsyncValidator(descriptor);
        const model = {};

        model[this.prop] = this.fieldValue;

        validator.validate(model, { firstFields: true}, (errors, invalidFields) => {
          this.validateState = !errors ? 'success' : 'error';
          this.validateMessage = errors ? errors[0].message : '';

          callback(this.validateMessage, invalidFields);
          this.elForm && this.elForm.$emit('validate', this.prop, !errors, this.validateMessage || null);
        });
      }

FormItem 有以下监听

this.$on('el.form.blur', this.onFieldBlur);
this.$on('el.form.change', this.onFieldChange);

所以,在本人的组件外面,触发这个事件就好了

this.dispatch('ElFormItem', 'el.form.change', self.fileList)

change 还是blur, 看 form rules 中的规定而定

dispath

dispatch: function dispatch(componentName, eventName, params) {
  var parent = this.$parent || this.$root;
  var name = parent.$options.componentName;

  while (parent && (!name || name !== componentName)) {
    parent = parent.$parent;

    if (parent) {name = parent.$options.componentName;}
  }
  if (parent) {parent.$emit.apply(parent, [eventName].concat(params));
  }
},

能够看出 dispath 就是始终死循环向上找父级组件。

正文完
 0