Просмотр исходного кода

Fix x-mask triggering update requests on load (#4481)

* Add fix

* Add a test
Josh Hanley 4 месяцев назад
Родитель
Сommit
b03a52d8a0
2 измененных файлов с 25 добавлено и 1 удалено
  1. 10 1
      packages/mask/src/index.js
  2. 15 0
      tests/cypress/integration/plugins/mask.spec.js

+ 10 - 1
packages/mask/src/index.js

@@ -40,7 +40,16 @@ export default function (Alpine) {
             }
 
             // Override x-model's initial value...
-            if (el._x_model) el._x_model.set(el.value)
+            if (el._x_model) {
+                // If the x-model value is the same, don't override it as that will trigger updates...
+                if (el._x_model.get() === el.value) return
+
+                // If the x-model value is `null` and the input value is an empty 
+                // string, don't override it as that will trigger updates...
+                if (el._x_model.get() === null && el.value === '') return
+
+                el._x_model.set(el.value)
+            }
         })
 
         const controller = new AbortController()

+ 15 - 0
tests/cypress/integration/plugins/mask.spec.js

@@ -89,6 +89,21 @@ test('x-mask with x-model with initial value',
     },
 )
 
+test('x-mask with x-model if initial value is null it should remain null',
+    [html`
+        <div x-data="{ value: null }">
+            <input x-mask="(999) 999-9999" x-model="value" id="1">
+            <input id="2" x-model="value">
+            <span id="3" x-text="value === null ? 'NULL' : value"></span>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').should(haveValue(''))
+        get('#2').should(haveValue(''))
+        get('#3').contains('NULL')
+    },
+)
+
 test('x-mask with a falsy input',
     [html`<input x-data x-mask="">`],
     ({ get }) => {