Backtestsvuerun-20261013-093701#14403

Issue #14403 Merged fix PR #14411 Run 13 Oct 2026 · run-20261013-093701 vuejs/core

Preserve input values entered during hydration

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches use the same approach. In `created`, they detect that the element is already in the DOM (meaning hydration is underway) and compare its live state to its server-rendered default. In `mounted`, they sync the user's value back to the model instead of overwriting the DOM.

Patch B only does this for `vModelText`, and only when `el.type` is 'text' or 'textarea'. Values typed during hydration are still lost for other input types (email, number, password, search, tel, url), and for checkbox, radio, and select. The issue covers forms with v-model inputs in general, so B fixes only the narrowest case. Its newline normalization is hand-rolled per type, and it passes only the `number` modifier to `castValue`. That is harmless here because `type=number` is excluded, but it shows how limited the coverage is.

Patch A covers text inputs of every type, textarea, checkbox (boolean, array and Set models, including several checkboxes sharing one stale model during a single mount pass), radio, single and multiple select, and `vModelDynamic`. It avoids false positives from browser value sanitization (range, color, newlines) by comparing against a pristine input built from the same attributes. It also reproduces the browser's default-selection rules for select (disabled options and optgroups, listbox size). It casts with both trim and number, and handles `type=number` correctly.

The `pendingModelValues` WeakMap and the select heuristics add some complexity and risk. However, they are justified by real cases, and the tests exercise them directly. The refactoring into `assignCheckboxValue` and `assignSelectValue` reuses the existing change-handler logic without changing its behavior.

On tests, A adds a thorough suite. It covers each directive, modifiers, untouched elements still receiving the client model value, browser-sanitized values, and a non-hydration client mount that must not sync. B adds one text-input test.

A is clearly the more complete and robust fix.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

12m 6s

Wall-clock time in the container

Full test suite

No new failures

1,771 passed · 1 skipped · 1,772 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

636vs 50 merged

Changed lines, ours vs merged

Vue version

3.5.27

Link to minimal reproduction

https://github.com/nuxt/nuxt/issues/29206

Steps to reproduce

user loads a page with a slow internet connection
starts entering some values ​​into the input with v-model
after all browser resources loaded - input v-model reset to default value

What is expected?

entered input value is preserved once hydration completes

What is actually happening?

input value is reset to its default value

System Info

Any additional comments?

This is affecting UX when interacting with inputs/forms in slowly loading apps, where values entered during hydration phase are erased and the progress is lost. I have been blocking all forms myself until mounted hook fires to workaround this issue - it would be great to not have to!

The two patches

Our patch+594 −42
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..2fe98883e 100644@@ -30,6 +30,10 @@ import {   renderSlot,   useCssVars,   vModelCheckbox,+  vModelDynamic,+  vModelRadio,+  vModelSelect,+  vModelText,   vShow,   withCtx,   withDirectives,@@ -1692,6 +1696,399 @@ describe('SSR hydration', () => {     expect((container.firstChild as any)._trueValue).toBe(true)   }) +  describe('preserve form values entered before hydration', () => {+    function hydrateAfterUserInput(+      html: string,+      interact: (container: HTMLElement) => void,+      render: () => any,+    ) {+      const container = document.createElement('div')+      container.innerHTML = html+      // the user interacts with the server-rendered markup before the app+      // hydrates (no listeners attached yet, so nothing is dispatched)+      interact(container)+      createSSRApp({ render }).mount(container)+      return container+    }++    test('text input', async () => {+      const text = ref('')+      const container = hydrateAfterUserInput(+        '<input value="">',+        c => ((c.firstChild as HTMLInputElement).value = 'typed'),+        () =>+          withDirectives(+            h('input', {+              'onUpdate:modelValue': (v: string) => (text.value = v),+            }),+            [[vModelText, text.value]],+          ),+      )+      const input = container.firstChild as HTMLInputElement+      expect(input.value).toBe('typed')+      expect(text.value).toBe('typed')+      await nextTick()+      expect(input.value).toBe('typed')++      // still reactive in both directions afterwards+      text.value = 'changed'+      await nextTick()+      expect(input.value).toBe('changed')+      input.value = 'again'+      triggerEvent('input', input)+      expect(text.value).toBe('again')+    })++    test('text input with number & trim modifiers', async () => {+      const num = ref<any>(1)+      const str = ref('a')+      const container = hydrateAfterUserInput(+        '<div><input type="number" value="1"><input value="a"></div>',+        c => {+          ;(c.querySelector('[type=number]') as HTMLInputElement).value = '42'+          ;(c.querySelector('input:not([type])') as HTMLInputElement).value =+            '  b  '+        },+        () =>+          h('div', [+            withDirectives(+              h('input', {+                type: 'number',+                'onUpdate:modelValue': (v: any) => (num.value = v),+              }),+              [[vModelText, num.value]],+            ),+            withDirectives(+              h('input', {+                'onUpdate:modelValue': (v: string) => (str.value = v),+              }),+              [[vModelText, str.value, '', { trim: true }]],+            ),+          ]),+      )+      expect(num.value).toBe(42)+      expect(str.value).toBe('b')+      await nextTick()+      expect(+        (container.querySelector('[type=number]') as HTMLInputElement).value,+      ).toBe('42')+    })++    test('textarea', async () => {+      const text = ref('default')+      const container = hydrateAfterUserInput(+        '<textarea>default</textarea>',+        c => ((c.firstChild as HTMLTextAreaElement).value = 'typed'),+        () =>+          withDirectives(+            h('textarea', {+              'onUpdate:modelValue': (v: string) => (text.value = v),+            }),+            [[vModelText, text.value]],+          ),+      )+      await nextTick()+      expect((container.firstChild as HTMLTextAreaElement).value).toBe(+        'typed',+      )+      expect(text.value).toBe('typed')+    })++    test('untouched input still gets client model value', async () => {+      const text = ref('client')+      const container = hydrateAfterUserInput(+        '<input value="server">',+        () => {},+        () =>+          withDirectives(+            h('input', {+              'onUpdate:modelValue': (v: string) => (text.value = v),+            }),+            [[vModelText, text.value]],+          ),+      )+      expect((container.firstChild as HTMLInputElement).value).toBe('client')+      expect(text.value).toBe('client')+      expect(`Hydration`).not.toHaveBeenWarned()+    })++    test('checkbox (boolean & array)', async () => {+      const bool = ref(false)+      const arr = ref<string[]>(['a'])+      const container = hydrateAfterUserInput(+        '<div><input type="checkbox"><input type="checkbox" value="a" checked>' ++          '<input type="checkbox" value="b"></div>',+        c => {+          const inputs = c.querySelectorAll('input')+          inputs[0].checked = true+          inputs[1].checked = false+          inputs[2].checked = true+        },+        () =>+          h('div', [+            withDirectives(+              h('input', {+                type: 'checkbox',+                'onUpdate:modelValue': (v: boolean) => (bool.value = v),+              }),+              [[vModelCheckbox, bool.value]],+            ),+            ...['a', 'b'].map(v =>+              withDirectives(+                h('input', {+                  type: 'checkbox',+                  value: v,+                  'onUpdate:modelValue': (v: string[]) => (arr.value = v),+                }),+                [[vModelCheckbox, arr.value]],+              ),+            ),+          ]),+      )+      expect(bool.value).toBe(true)+      expect(arr.value).toEqual(['b'])+      await nextTick()+      const inputs = container.querySelectorAll('input')+      expect(inputs[0].checked).toBe(true)+      expect(inputs[1].checked).toBe(false)+      expect(inputs[2].checked).toBe(true)+    })++    test('checkbox (Set)', () => {+      const set = ref(new Set(['a']))+      hydrateAfterUserInput(+        '<div><input type="checkbox" value="a" checked>' ++          '<input type="checkbox" value="b"></div>',+        c => {+          const inputs = c.querySelectorAll('input')+          inputs[0].checked = false+          inputs[1].checked = true+        },+        () =>+          h(+            'div',+            ['a', 'b'].map(v =>+              withDirectives(+                h('input', {+                  type: 'checkbox',+                  value: v,+                  'onUpdate:modelValue': (v: Set<string>) => (set.value = v),+                }),+                [[vModelCheckbox, set.value]],+              ),+            ),+          ),+      )+      expect([...set.value]).toEqual(['b'])+    })++    test('radio', async () => {+      const picked = ref('a')+      const container = hydrateAfterUserInput(+        '<div><input type="radio" value="a" checked>' ++          '<input type="radio" value="b"></div>',+        c => (c.querySelectorAll('input')[1].checked = true),+        () =>+          h(+            'div',+            ['a', 'b'].map(v =>+              withDirectives(+                h('input', {+                  type: 'radio',+                  value: v,+                  'onUpdate:modelValue': (v: string) => (picked.value = v),+                }),+                [[vModelRadio, picked.value]],+              ),+            ),+          ),+      )+      expect(picked.value).toBe('b')+      await nextTick()+      const inputs = container.querySelectorAll('input')+      expect(inputs[0].checked).toBe(false)+      expect(inputs[1].checked).toBe(true)+    })++    test('select (single & multiple)', async () => {+      const single = ref('a')+      const multi = ref<string[]>([])+      const container = hydrateAfterUserInput(+        '<div><select><option value="a" selected>a</option>' ++          '<option value="b">b</option></select>' ++          '<select multiple><option value="a">a</option>' ++          '<option value="b">b</option></select></div>',+        c => {+          const [s, m] = c.querySelectorAll('select')+          s.selectedIndex = 1+          m.options[0].selected = true+          m.options[1].selected = true+        },+        () =>+          h('div', [+            withDirectives(+              h(+                'select',+                { 'onUpdate:modelValue': (v: string) => (single.value = v) },+                ['a', 'b'].map(v => h('option', { value: v }, v)),+              ),+              [[vModelSelect, single.value]],+            ),+            withDirectives(+              h(+                'select',+                {+                  multiple: true,+                  'onUpdate:modelValue': (v: string[]) => (multi.value = v),+                },+                ['a', 'b'].map(v => h('option', { value: v }, v)),+              ),+              [[vModelSelect, multi.value]],+            ),+          ]),+      )+      expect(single.value).toBe('b')+      expect(multi.value).toEqual(['a', 'b'])+      await nextTick()+      const [s, m] = container.querySelectorAll('select')+      expect(s.value).toBe('b')+      expect(m.options[0].selected).toBe(true)+      expect(m.options[1].selected).toBe(true)+    })++    test('untouched select still gets client model value', () => {+      const single = ref('b')+      const container = hydrateAfterUserInput(+        '<select><option value="a">a</option>' ++          '<option value="b">b</option></select>',+        () => {},+        () =>+          withDirectives(+            h(+              'select',+              { 'onUpdate:modelValue': (v: string) => (single.value = v) },+              ['a', 'b'].map(v => h('option', { value: v }, v)),+            ),+            [[vModelSelect, single.value]],+          ),+      )+      expect((container.firstChild as HTMLSelectElement).value).toBe('b')+      expect(single.value).toBe('b')+    })++    test('untouched inputs with browser-sanitized values keep model', () => {+      const range = ref(null)+      const color = ref('#FFAA00')+      const container = hydrateAfterUserInput(+        '<div><input type="range"><input type="color" value="#FFAA00"></div>',+        () => {},+        () =>+          h('div', [+            withDirectives(+              h('input', {+                type: 'range',+                'onUpdate:modelValue': (v: any) => (range.value = v),+              }),+              [[vModelText, range.value]],+            ),+            withDirectives(+              h('input', {+                type: 'color',+                'onUpdate:modelValue': (v: string) => (color.value = v),+              }),+              [[vModelText, color.value]],+            ),+          ]),+      )+      expect(range.value).toBe(null)+      expect(color.value).toBe('#FFAA00')+      expect(container.querySelectorAll('input')[1].value).toBe('#ffaa00')+    })++    test('untouched select without default selection keeps model', () => {+      const listbox = ref(null)+      const grouped = ref(null)+      hydrateAfterUserInput(+        '<div><select size="3"><option value="a">a</option></select>' ++          '<select><optgroup disabled><option value="a">a</option></optgroup>' ++          '<option value="b">b</option></select></div>',+        () => {},+        () =>+          h('div', [+            withDirectives(+              h(+                'select',+                {+                  size: 3,+                  'onUpdate:modelValue': (v: any) => (listbox.value = v),+                },+                [h('option', { value: 'a' }, 'a')],+              ),+              [[vModelSelect, listbox.value]],+            ),+            withDirectives(+              h(+                'select',+                { 'onUpdate:modelValue': (v: any) => (grouped.value = v) },+                [+                  h('optgroup', { disabled: true }, [+                    h('option', { value: 'a' }, 'a'),+                  ]),+                  h('option', { value: 'b' }, 'b'),+                ],+              ),+              [[vModelSelect, grouped.value]],+            ),+          ]),+      )+      expect(listbox.value).toBe(null)+      expect(grouped.value).toBe(null)+    })++    test('client mount does not sync DOM state to model', () => {+      const grouped = ref(null)+      const root = document.createElement('div')+      runtimeDom+        .createApp({+          render: () =>+            withDirectives(+              h(+                'select',+                { 'onUpdate:modelValue': (v: any) => (grouped.value = v) },+                [+                  h('optgroup', { disabled: true }, [+                    h('option', { value: 'a' }, 'a'),+                  ]),+                  h('option', { value: 'b' }, 'b'),+                ],+              ),+              [[vModelSelect, grouped.value]],+            ),+        })+        .mount(root)+      expect(grouped.value).toBe(null)+    })++    test('dynamic v-model', async () => {+      const text = ref('')+      const container = hydrateAfterUserInput(+        '<input type="text" value="">',+        c => ((c.firstChild as HTMLInputElement).value = 'typed'),+        () =>+          withDirectives(+            h('input', {+              type: 'text',+              'onUpdate:modelValue': (v: string) => (text.value = v),+            }),+            [[vModelDynamic, text.value]],+          ),+      )+      expect(text.value).toBe('typed')+      await nextTick()+      expect((container.firstChild as HTMLInputElement).value).toBe('typed')+    })+  })+   test('force hydrate checkbox with indeterminate', () => {     const { container } = mountWithHydration(       '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..ec4b5619f 100644@@ -38,13 +38,86 @@ function onCompositionEnd(e: Event) { }  const assignKey: unique symbol = Symbol('_assign')+// set in `created` when the element's current state differs from its+// server-rendered default, i.e. the user interacted with it before hydration+const userModifiedKey: unique symbol = Symbol('_userModified')  type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<-  T & { [assignKey]: AssignerFn; _assigning?: boolean },+  T & {+    [assignKey]: AssignerFn+    [userModifiedKey]?: boolean+    _assigning?: boolean+  },   any,   Modifiers > +// in `created`, the element is already in the DOM only when hydrating (a+// freshly created element is inserted after its props are patched)+const isHydrating = (el: Element) => el.parentNode != null++function isTextModified(el: HTMLInputElement | HTMLTextAreaElement): boolean {+  // custom elements may not implement `defaultValue`+  if (+    !isHydrating(el) ||+    el.defaultValue == null ||+    el.value === el.defaultValue+  ) {+    return false+  }+  if (el.tagName !== 'INPUT') return true+  // browsers sanitize the value attribute (e.g. range, color, newlines), so+  // compare against a pristine input built from the same attributes+  const pristine = el.ownerDocument.createElement('input')+  for (const { name, value } of Array.from(el.attributes)) {+    pristine.setAttribute(name, value)+  }+  return el.value !== pristine.value+}++function isCheckedModified(el: HTMLInputElement): boolean {+  return (+    isHydrating(el) &&+    el.defaultChecked != null &&+    el.checked !== el.defaultChecked+  )+}++/**+ * Returns true if a <select>'s selection differs from the one described by its+ * options' `selected` attributes (i.e. what the server rendered).+ */+function isSelectModified(el: HTMLSelectElement): boolean {+  if (!isHydrating(el)) return false+  const options = el.options+  if (el.multiple) {+    for (let i = 0; i < options.length; i++) {+      if (options[i].selected !== options[i].defaultSelected) return true+    }+    return false+  }+  // single select: browsers select the last option with a `selected`+  // attribute, otherwise (unless displayed as a list box) the first+  // non-disabled option.+  let defaultIndex = -1+  for (let i = 0; i < options.length; i++) {+    if (options[i].defaultSelected) defaultIndex = i+  }+  if (defaultIndex === -1 && !(el.size > 1)) {+    for (let i = 0; i < options.length; i++) {+      const parent = options[i].parentNode as HTMLOptGroupElement+      if (+        !options[i].disabled &&+        !(parent.tagName === 'OPTGROUP' && parent.disabled)+      ) {+        defaultIndex = i+        break+      }+    }+  }+  return el.selectedIndex !== defaultIndex+}+ function castValue(value: string, trim?: boolean, number?: boolean | null) {   if (trim) value = value.trim()   if (number) value = looseToNumber(value)@@ -58,6 +131,9 @@ export const vModelText: ModelDirective<   'trim' | 'number' | 'lazy' > = {   created(el, { modifiers: { lazy, trim, number } }, vnode) {+    // during hydration the user may have already typed into the+    // server-rendered element - record it so mounted won't overwrite it.+    el[userModifiedKey] = isTextModified(el)     el[assignKey] = getModelAssigner(vnode)     const castToNumber =       number || (vnode.props && vnode.props.type === 'number')@@ -81,7 +157,19 @@ export const vModelText: ModelDirective<     }   },   // set value on mounted so it's after min/max for type="range"-  mounted(el, { value }) {+  mounted(el, { value, modifiers: { trim, number } }, vnode) {+    if (el[userModifiedKey]) {+      el[userModifiedKey] = false+      // sync the value entered before hydration back to the model+      el[assignKey](+        castValue(+          el.value,+          trim,+          number || (vnode.props && vnode.props.type === 'number'),+        ),+      )+      return+    }     el.value = value == null ? '' : value   },   beforeUpdate(@@ -125,43 +213,84 @@ export const vModelCheckbox: ModelDirective<HTMLInputElement> = {   // #4096 array checkboxes need to be deep traversed   deep: true,   created(el, _, vnode) {+    // user may have toggled the server-rendered checkbox before hydration+    el[userModifiedKey] = isCheckedModified(el)     el[assignKey] = getModelAssigner(vnode)     addEventListener(el, 'change', () => {-      const modelValue = (el as any)._modelValue-      const elementValue = getValue(el)-      const checked = el.checked-      const assign = el[assignKey]-      if (isArray(modelValue)) {-        const index = looseIndexOf(modelValue, elementValue)-        const found = index !== -1-        if (checked && !found) {-          assign(modelValue.concat(elementValue))-        } else if (!checked && found) {-          const filtered = [...modelValue]-          filtered.splice(index, 1)-          assign(filtered)-        }-      } else if (isSet(modelValue)) {-        const cloned = new Set(modelValue)-        if (checked) {-          cloned.add(elementValue)-        } else {-          cloned.delete(elementValue)-        }-        assign(cloned)-      } else {-        assign(getCheckboxValue(el, checked))-      }+      assignCheckboxValue(el)     })   },   // set initial checked on mount to wait for true-value/false-value-  mounted: setChecked,+  mounted(el, binding, vnode) {+    if (el[userModifiedKey]) {+      el[userModifiedKey] = false+      const { value } = binding+      // checkboxes sharing an array / Set model all receive the same stale+      // binding value in this mount pass - build on top of what earlier+      // checkboxes of the group already assigned instead.+      const shared = isArray(value) || isSet(value)+      ;(el as any)._modelValue =+        shared && pendingModelValues.has(value)+          ? pendingModelValues.get(value)+          : value+      // value / true-value / false-value are patched by now+      const assigned = assignCheckboxValue(el)+      if (shared && assigned !== undefined) {+        if (!pendingModelValues.has(value)) {+          nextTick(() => pendingModelValues.delete(value))+        }+        pendingModelValues.set(value, assigned)+      }+      return+    }+    setChecked(el, binding, vnode)+  },   beforeUpdate(el, binding, vnode) {     el[assignKey] = getModelAssigner(vnode)     setChecked(el, binding, vnode)   }, } +// array / Set model values assigned by checkboxes during the current mount+// pass, keyed by the original (stale) model value+const pendingModelValues = new WeakMap<object, any>()++/**+ * Assigns the checkbox state to the model and returns the assigned value+ * (undefined if nothing was assigned).+ */+function assignCheckboxValue(+  el: HTMLInputElement & { [assignKey]: AssignerFn },+): any {+  const modelValue = (el as any)._modelValue+  const elementValue = getValue(el)+  const checked = el.checked+  const assign = el[assignKey]+  let newValue: any+  if (isArray(modelValue)) {+    const index = looseIndexOf(modelValue, elementValue)+    const found = index !== -1+    if (checked && !found) {+      assign((newValue = modelValue.concat(elementValue)))+    } else if (!checked && found) {+      newValue = [...modelValue]+      newValue.splice(index, 1)+      assign(newValue)+    }+  } else if (isSet(modelValue)) {+    newValue = new Set(modelValue)+    if (checked) {+      newValue.add(elementValue)+    } else {+      newValue.delete(elementValue)+    }+    assign(newValue)+  } else {+    assign((newValue = getCheckboxValue(el, checked)))+  }+  return newValue+}+ function setChecked(   el: HTMLInputElement,   { value, oldValue }: DirectiveBinding,@@ -189,12 +318,23 @@ function setChecked(  export const vModelRadio: ModelDirective<HTMLInputElement> = {   created(el, { value }, vnode) {-    el.checked = looseEqual(value, vnode.props!.value)+    // keep a selection the user made before hydration+    if (!(el[userModifiedKey] = isCheckedModified(el))) {+      el.checked = looseEqual(value, vnode.props!.value)+    }     el[assignKey] = getModelAssigner(vnode)     addEventListener(el, 'change', () => {       el[assignKey](getValue(el))     })   },+  mounted(el) {+    if (el[userModifiedKey]) {+      el[userModifiedKey] = false+      // only the radio the user selected syncs its value (patched by now) to+      // the model; the one it unchecked has nothing to report.+      if (el.checked) el[assignKey](getValue(el))+    }+  },   beforeUpdate(el, { value, oldValue }, vnode) {     el[assignKey] = getModelAssigner(vnode)     if (value !== oldValue) {@@ -208,19 +348,11 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = {   deep: true,   created(el, { value, modifiers: { number } }, vnode) {     ;(el as any)._modelValue = value+    // <option>s are already present here during hydration, so we can tell+    // whether the user changed the selection before hydration.+    el[userModifiedKey] = isSelectModified(el)     addEventListener(el, 'change', () => {-      const selectedVal = Array.prototype.filter-        .call(el.options, (o: HTMLOptionElement) => o.selected)-        .map((o: HTMLOptionElement) =>-          number ? looseToNumber(getValue(o)) : getValue(o),-        )-      el[assignKey](-        el.multiple-          ? isSet((el as any)._modelValue)-            ? new Set(selectedVal)-            : selectedVal-          : selectedVal[0],-      )+      assignSelectValue(el, number)       el._assigning = true       nextTick(() => {         el._assigning = false@@ -230,7 +362,12 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = {   },   // set value in mounted & updated because <select> relies on its children   // <option>s.-  mounted(el, { value }) {+  mounted(el, { value, modifiers: { number } }) {+    if (el[userModifiedKey]) {+      el[userModifiedKey] = false+      assignSelectValue(el, number)+      return+    }     setSelected(el, value)   },   beforeUpdate(el, { value }, vnode) {@@ -244,6 +381,24 @@ export const vModelSelect: ModelDirective<HTMLSelectElement, 'number'> = {   }, } +function assignSelectValue(+  el: HTMLSelectElement & { [assignKey]: AssignerFn },+  number: boolean | undefined,+) {+  const selectedVal = Array.prototype.filter+    .call(el.options, (o: HTMLOptionElement) => o.selected)+    .map((o: HTMLOptionElement) =>+      number ? looseToNumber(getValue(o)) : getValue(o),+    )+  el[assignKey](+    el.multiple+      ? isSet((el as any)._modelValue)+        ? new Set(selectedVal)+        : selectedVal+      : selectedVal[0],+  )+}+ function setSelected(el: HTMLSelectElement, value: any) {   const isMultiple = el.multiple   const isArrayValue = isArray(value) 
Merged fix · PR #14411+47 −3
packages/runtime-core/__tests__/hydration.spec.tsindex 537ba236c..49c39bdd6 100644@@ -1692,6 +1692,24 @@ describe('SSR hydration', () => {     expect((container.firstChild as any)._trueValue).toBe(true)   }) +  test('preserves text entered before v-model hydration', async () => {+    const state = reactive({ text: 'server value' })+    const App = {+      setup: () => state,+      template: `<input v-model="text">`,+    }+    const container = document.createElement('div')+    container.innerHTML = await renderToString(h(App))+    const input = container.firstChild as HTMLInputElement+    input.value = 'user value'++    createSSRApp(App).mount(container)+    await nextTick()++    expect(input.value).toBe('user value')+    expect(state.text).toBe('user value')+  })+   test('force hydrate checkbox with indeterminate', () => {     const { container } = mountWithHydration(       '<input type="checkbox" indeterminate>',packages/runtime-dom/src/directives/vModel.tsindex 766db6bfe..eeb248f28 100644@@ -38,9 +38,14 @@ function onCompositionEnd(e: Event) { }  const assignKey: unique symbol = Symbol('_assign')+const initialValueKey: unique symbol = Symbol('_initialValue')  type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<-  T & { [assignKey]: AssignerFn; _assigning?: boolean },+  T & {+    [assignKey]: AssignerFn+    [initialValueKey]?: string+    _assigning?: boolean+  },   any,   Modifiers >@@ -58,6 +63,16 @@ export const vModelText: ModelDirective<   'trim' | 'number' | 'lazy' > = {   created(el, { modifiers: { lazy, trim, number } }, vnode) {+    // During hydration, created runs on an element already in the DOM.+    if (el.parentNode) {+      if (el.type === 'text') {+        // Text inputs strip CR/LF from value, while defaultValue retains them.+        el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, '')+      } else if (el.type === 'textarea') {+        // Textareas normalize CRLF/CR to LF in value.+        el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, '\n')+      }+    }     el[assignKey] = getModelAssigner(vnode)     const castToNumber =       number || (vnode.props && vnode.props.type === 'number')@@ -81,8 +96,19 @@ export const vModelText: ModelDirective<     }   },   // set value on mounted so it's after min/max for type="range"-  mounted(el, { value }) {-    el.value = value == null ? '' : value+  mounted(el, { value, modifiers: { trim, number } }) {+    const newValue = value == null ? '' : value+    const initialValue = el[initialValueKey]+    delete el[initialValueKey]+    if (+      initialValue !== undefined &&+      (el.type === 'text' || el.type === 'textarea') &&+      el.value !== initialValue+    ) {+      el[assignKey](castValue(el.value, trim, number))+    } else {+      el.value = newValue+    }   },   beforeUpdate(     el,