Преглед на файлове

Initialize x-if AFTER being added to the DOM so x-ref works

Caleb Porzio преди 3 години
родител
ревизия
143f10d897
променени са 3 файла, в които са добавени 21 реда и са изтрити 4 реда
  1. 2 2
      packages/alpinejs/src/directives/x-for.js
  2. 4 2
      packages/alpinejs/src/directives/x-if.js
  3. 15 0
      tests/cypress/integration/directives/x-if.spec.js

+ 2 - 2
packages/alpinejs/src/directives/x-for.js

@@ -171,10 +171,10 @@ function loop(el, iteratorNames, evaluateItems, evaluateKey) {
 
             addScopeToNode(clone, reactive(scope), templateEl)
 
-            initTree(clone)
-
             mutateDom(() => {
                 lastEl.after(clone)
+
+                initTree(clone)
             })
 
             lookup[key] = clone

+ 4 - 2
packages/alpinejs/src/directives/x-if.js

@@ -14,9 +14,11 @@ directive('if', (el, { expression }, { effect, cleanup }) => {
 
         addScopeToNode(clone, {}, el)
 
-        initTree(clone)
+        mutateDom(() => {
+            el.after(clone)
 
-        mutateDom(() => el.after(clone))
+            initTree(clone)
+        })
 
         el._x_currentIfEl = clone
 

+ 15 - 0
tests/cypress/integration/directives/x-if.spec.js

@@ -36,3 +36,18 @@ test('x-if inside x-for allows nested directives',
         get('span').should(haveText('1'))
     }
 )
+
+test('x-if initializes after being added to the DOM to allow x-ref to work',
+    html`
+        <div x-data="{}">
+            <template x-if="true">
+                <ul x-ref="listbox" data-foo="bar">
+                    <li x-text="$refs.listbox.dataset.foo"></li>
+                </ul>
+            </template>
+        </div>
+    `,
+    ({ get }) => {
+        get('li').should(haveText('bar'))
+    }
+)