瀏覽代碼

input-number auto adjust min max value

baiyaaaaa 8 年之前
父節點
當前提交
accebb772b
共有 2 個文件被更改,包括 16 次插入21 次删除
  1. 15 20
      packages/input-number/src/input-number.vue
  2. 1 1
      test/unit/specs/input-number.spec.js

+ 15 - 20
packages/input-number/src/input-number.vue

@@ -96,26 +96,20 @@
       }
     },
     data() {
-      // correct the init value
-      let value = this.value;
-      if (value < this.min) {
-        this.$emit('input', this.min);
-        value = this.min;
-      }
-      if (value > this.max) {
-        this.$emit('input', this.max);
-        value = this.max;
-      }
-
       return {
-        currentValue: value
+        currentValue: 0
       };
     },
     watch: {
-      value(value) {
-        const newVal = Number(value);
-        if (!isNaN(newVal) && newVal <= this.max && newVal >= this.min) {
+      value: {
+        immediate: true,
+        handler(value) {
+          let newVal = Number(value);
+          if (isNaN(newVal)) return;
+          if (newVal >= this.max) newVal = this.max;
+          if (newVal <= this.min) newVal = this.min;
           this.currentValue = newVal;
+          this.$emit('input', newVal);
         }
       }
     },
@@ -178,11 +172,12 @@
       },
       setCurrentValue(newVal) {
         const oldVal = this.currentValue;
-        if (newVal <= this.max && newVal >= this.min && oldVal !== newVal) {
-          this.$emit('change', newVal, oldVal);
-          this.$emit('input', newVal);
-          this.currentValue = newVal;
-        }
+        if (newVal >= this.max) newVal = this.max;
+        if (newVal <= this.min) newVal = this.min;
+        if (oldVal === newVal) return;
+        this.$emit('change', newVal, oldVal);
+        this.$emit('input', newVal);
+        this.currentValue = newVal;
       },
       handleInput(value) {
         const newVal = Number(value);

+ 1 - 1
test/unit/specs/input-number.spec.js

@@ -249,7 +249,7 @@ describe('InputNumber', () => {
     const inputNumber = vm.$refs.inputNumber;
     vm.value = 100;
     vm.$nextTick(_ => {
-      expect(inputNumber.currentValue).to.be.equal(5);
+      expect(inputNumber.currentValue).to.be.equal(10);
       vm.value = 4;
 
       vm.$nextTick(_ => {