What are the contents of $items in PHP; is it already JSON encoded???
Jun 16, 2023
8
Level 63
Problem to import an array inside an AlpineJS component
Hello,
I'm in trouble with importing an array inside an AlpineJS component.
Here is the component and you will see the line with the text // here is the problem.
Like this, it's impossible to use the items JS variable to loop in or to find an item. I have tried to replace by @json($items), but it doesn't work better. I have also tried JSON.parse, nothing seems to work.
<div
class="w-full relative flex flex-col gap-1 select-none"
x-data="{
show: false,
label: '{{ $label }}',
nochoiceLabel: '{{ $nochoiceLabel }}',
selectedItemLabel: '{{ $nochoiceLabel }}',
items: '{{ $items }}', // here is the problem
item_id: @entangle($attributes->wire('model')),
}"
x-init="
console.log(items);
$watch('item_id', function (value) {
// this line is not working
const selectedItem = this.items.find(function (item) {
return item.id == value;
});
});
"
@click.away="show=false"
>
<label class="text-gray-500" for="item_id" x-html="label"></label>
<div class="flex justify-between items-center px-3 py-1 border border-black rounded cursor-pointer" @click="show = !show">
<label x-html="selectedItemLabel"></label>
<span class="text-xs"><i class="fa-solid fa-chevron-down"></i></span>
</div>
<template x-if="true">
<ul class="absolute top-16 left-0 w-full max-h-60 overflow-y-auto bg-slate-800 border-2 border-slate-700 text-slate-300 rounded cursor-pointer" x-show="show" x-transition>
<li class="w-full px-3 py-1 first:rounded-t last:rounded-b hover:bg-lime-500 hover:text-black" @click="item_id=0">{{ $nochoiceLabel }}</li>
@foreach($items as $item)
<li class="w-full px-3 py-1 first:rounded-t last:rounded-b hover:bg-lime-500 hover:text-black" @click="item_id={{ $item['id'] }}">{{ $item['name'] }}</li>
@endforeach
</ul>
</template>
</div>
A console log of the items JS variable gives this.
[{"id":5,"name":"Animation"},{"id":3,"name":"Coaching"},{"id":2,"name":"Conseil"},{"id":4,"name":"Développement"},{"id":1,"name":"Formation"}]
What can I do ?
Thanks for your help.
V
Please or to participate in this conversation.