解决 Vue props 校验依赖问题

实现某组件传入 prop 需要校验,该校验依赖于传入的其他 props

方案如下:

class Validator {
  constructor(min, max) {
    this.min = min
    this.max = max
  }

  validator(val) {
    return val <= this.max && (this.max - this.min) % val === 0
  }
}

const validator = new Validator()

export default {
  name: 'Home',
  props: {
    min: {
      default: 0,
      validator: val => {
        validator.min = val
        return typeof val === 'number'
      }
    },
    max: {
      default: 100,
      validator: val => {
        validator.max = val
        return typeof val === 'number'
      }
    },
    step: {
      type: Number,
      default: 1,
      validator: val => validator.validator(val)
    }
  }
}

你可能感兴趣的:(解决 Vue props 校验依赖问题)