vue

开发场景

  • 一个 input 框,用户输入小数时,对满足条件的自动转换为百分数
  • 同时允许用户直接输入百分数
  • 并且绑定的数据为数值类型
  • 经验:过去使用 input 框的 blur 事件来改变用户输入值,但是当用户在 input 具有焦点时点击提交按钮,会导致提交按钮的 submit 事件早于输入框的 blur 事件触发,使传到后端的数据有误
export default {
  props: {
    value: {
      default: ''
    },
    formatFun: {
      default: null
    },
    reverseFormatFun: {
      default: null
    }
  },
  data() {
    return {
      innerValue: ''
    };
  },
  methods: {
    setValue(v) {
      this.innerValue = v;
      const ret = this.reverseFormatFun ? this.reverseFormatFun(v) : v;
      this.$emit('input', ret);
    }
  },
  computed: {
    showValue() {
      return this.innerValue
        ? this.innerValue
        : this.formatFun
        ? this.formatFun(this.value)
        : this.value;
    },
    props() {
      return {
        props: {
          ...this.$attrs,
          value: this.showValue
        }
      };
    },
    listeners() {
      return {
        on: {
          ...this.$listeners,
          input: this.setValue,
          blur: () => (this.innerValue = '')
        }
      };
    }
  },
  render() {
    return <el-input {...this.props} {...this.listeners}></el-input>;
  }
};
原文地址:https://www.cnblogs.com/qq3279338858/p/14153398.html