From 4733a78bc03413019c5eb0d3f2715d95e5a74007 Mon Sep 17 00:00:00 2001 From: chenzhihui <18281682921@qqcom> Date: Tue, 1 Nov 2022 17:57:45 +0800 Subject: [PATCH] fix(compiler-dom):v-model can update correctly when the element is an input of type number (#7003) --- .../__tests__/directives/vModel.spec.ts | 54 +++++++++++++++++++ packages/runtime-dom/src/directives/vModel.ts | 10 +++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/packages/runtime-dom/__tests__/directives/vModel.spec.ts b/packages/runtime-dom/__tests__/directives/vModel.spec.ts index f5a0c6fadcc..53fb26a9cf5 100644 --- a/packages/runtime-dom/__tests__/directives/vModel.spec.ts +++ b/packages/runtime-dom/__tests__/directives/vModel.spec.ts @@ -101,6 +101,60 @@ describe('vModel', () => { expect(data.value).toEqual(1) }) + it('should work with number input and be able to update rendering correctly', async () => { + const setValue1 = function (this: any, value: any) { + this.value1 = value + } + const setValue2 = function (this: any, value: any) { + this.value2 = value + } + const component = defineComponent({ + data() { + return { value1: 1.002, value2: 1.002 } + }, + render() { + return [ + withVModel( + h('input', { + id:'input_num1', + type: 'number', + 'onUpdate:modelValue': setValue1.bind(this) + }), + this.value1 + ), + withVModel( + h('input', { + id:'input_num2', + type: 'number', + 'onUpdate:modelValue': setValue2.bind(this) + }), + this.value2 + ) + ] + } + }) + render(h(component), root) + const data = root._vnode.component.data + + const inputNum1 = root.querySelector('#input_num1')! + expect(inputNum1.value).toBe('1.002') + + const inputNum2 = root.querySelector('#input_num2')! + expect(inputNum2.value).toBe('1.002') + + inputNum1.value = '1.00' + triggerEvent('input', inputNum1) + await nextTick() + expect(data.value1).toBe(1) + + inputNum2.value = '1.00' + triggerEvent('input', inputNum2) + await nextTick() + expect(data.value2).toBe(1) + + expect(inputNum1.value).toBe('1.00') + }) + it('should work with multiple listeners', async () => { const spy = jest.fn() const component = defineComponent({ diff --git a/packages/runtime-dom/src/directives/vModel.ts b/packages/runtime-dom/src/directives/vModel.ts index 722b4d9b44c..0bb4d3ea19c 100644 --- a/packages/runtime-dom/src/directives/vModel.ts +++ b/packages/runtime-dom/src/directives/vModel.ts @@ -93,8 +93,14 @@ export const vModelText: ModelDirective< } } const newValue = value == null ? '' : value - if (el.value !== newValue) { - el.value = newValue + if (el.type === 'number' && vnode.type === 'input') { + if (Number(el.value) !== newValue) { + el.value = newValue + } + } else { + if (el.value !== newValue) { + el.value = newValue + } } } }