Alpine nested x-data

Viewed 8487

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.

4 Answers

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

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

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>
Related