6

I am trying to learn Alpine and I am testing out nested x-data. I came across a GitHub issue with nested x-data. They provided a solution which I wanted to try out myself. However, when I try to replicate the code, it didn't print anything. There are no errors in the console too. Can anyone guide me as to what I did wrong?

<div x-data="{foo: 'bar'}">
        <div x-data="{ }">
            <span x-text="foo"></span>
        </div>
</div>

I also tried using the $el property but it produced the same result.

Reon Low Yiyuan
  • 123
  • 2
  • 2
  • 10
  • Should make a note this is alpinejs v2. Merely upgrading to alpinejs v3 will result in the expected nesting behavior. – Kevin Y Feb 16 '22 at 21:37

4 Answers4

6

As @LaundroMat mentioned, helper functions are built for these purpose.

<div x-data="{foo: 'bar'}">
    <div x-data="{localFoo: 'local bar'}">
        <span x-text="$parent.foo"></span>
        <p x-text="localFoo"></p>
    </div>
</div>

codepen for reference

chisim
  • 61
  • 2
  • 3
5

In version 3 of alpinejs this issue has been solved. Nothing needs to be done.

weisk
  • 2,468
  • 1
  • 18
  • 18
Puneet Sharma
  • 307
  • 3
  • 9
3

Nesting in Alpine.js doesn't work as it does in Vue/React. When you nest a component, it doesn't have access to the parent's data, only its own.

You need to add the foo property to the nested x-data like so

<div x-data="{ }">
        <div x-data="{ foo: 'bar' }">
            <span x-text="foo"></span>
        </div>
</div>
Hugo
  • 3,500
  • 1
  • 14
  • 28
  • Is there any way to append or remove new value to parent x-data in child element? Like list.append() works. – Ulvi Jan 14 '21 at 15:15
1

You could use the $component/$parent helper from the Alpine Magic Helpers collection.

Mathieu Dhondt
  • 8,405
  • 5
  • 37
  • 58