user3818576
user3818576

Reputation: 3401

How to get proper data when using blade components and alpinejs?

I'm new in components and alpine in laravel. I have data from controller $positions.

$positions = [
        ['id' => 1, 'content' => 'king'],
        ['id' => 2, 'content' => 'lord']
    ];

When I pass it to laravel blade. here is my code

<div class="row">
        <div class="col">
            @foreach($list as $key => $position)
                <x-list :position="$position"/>
            @endforeach
        </div>
    </div>

I have component name it <x-list/> with a prop position, and here is the code of my x-list component

<div class="red w-60 mb-1">
    <div x-data="positionData()" class="relative">
        <button @click="submit()" class="p-2">Submit</button>
    </div>
</div>
<script>;
    var position = @json($position);
    function positionData() {
        return {    
            submit() {
                console.log(position);
            },
        };
    }
</script>

It is just very simple code but when I click the submit button, the data I get is the last position from the list ['id' => 2, 'content' => 'lord'], even I click position 1 the data I get is still position 2 data. I don't know what happen now. I try to search it in google to fix it but I can't find the right answer on this.

Upvotes: 0

Views: 3831

Answers (1)

Hugo
Hugo

Reputation: 3888

I think the issue in this case is that the positionData function is being overwritten on each iteration of x-list (since each of the components is creating a new window.positionData function).

To solve it you could do:

<div class="red w-60 mb-1">
    <div x-data="positionData(@json($position))" class="relative">
        <button @click="submit()" class="p-2">Submit</button>
    </div>
</div>
<script>;
    function positionData(position) {
        return {    
            submit() {
                console.log(position);
            },
        };
    }
</script>

Specifically, you should probably move the <script></script> out of the x-list component so that it doesn't get re-created for each component (it should only be added to the page once).

Upvotes: 1

Related Questions