1
0
Caleb Porzio 3 жил өмнө
parent
commit
5061521f1d

+ 4 - 0
packages/alpinejs/src/magics/$root.js

@@ -0,0 +1,4 @@
+import { closestRoot } from "../lifecycle";
+import { magic } from "../magics";
+
+magic('root', el => closestRoot(el))

+ 1 - 0
packages/alpinejs/src/magics/index.js

@@ -2,5 +2,6 @@ import './$nextTick'
 import './$dispatch'
 import './$watch'
 import './$store'
+import './$root'
 import './$refs'
 import './$el'

+ 21 - 0
packages/docs/src/en/magics/root.md

@@ -0,0 +1,21 @@
+---
+order: 7
+prefix: $
+title: root
+---
+
+# `$root`
+
+`$root` is a magic property that can be used to retrieve the root element of any Alpine component. In other words the closest element up the DOM tree that contains `x-data`.
+
+```alpine
+<div x-data data-message="Hello World!">
+    <button @click="alert($root.dataset.message)">Say Hi</button>
+</div>
+```
+
+<!-- START_VERBATIM -->
+<div x-data data-message="Hello World!" class="demo">
+    <button @click="alert($root.dataset.message)">Say Hi</button>
+</div>
+<!-- END_VERBATIM -->

+ 14 - 0
tests/cypress/integration/magics/$root.spec.js

@@ -0,0 +1,14 @@
+import { haveText, html, test } from '../../utils'
+
+test('$root returns the root element of the component',
+    html`
+        <div x-data data-message="foo">
+            <button @click="$el.innerText = $root.dataset.message">click me</button>
+        </div>
+    `,
+    ({ get }) => {
+        get('button').should(haveText('click me'))
+        get('button').click()
+        get('button').should(haveText('foo'))
+    }
+)