Level 58
The issue in the code is that the this keyword inside the indexOf function refers to the function itself, not the AlpineJS component. To fix this, you can use an arrow function instead, which preserves the value of this from the surrounding context.
Here's the updated code:
<div
class="space-y-4"
x-data="{
tabs: {{ json_encode($tabs) }},
visibleTab: '{{ $defaultTab }}',
animation: {
['x-transition:enter']: 'transition duration-200 ease-in',
['x-transition:enter-start']: 'opacity-0',
['x-transition:enter-end']: 'opacity-100',
},
prev() {
console.log(this.visibleTab); // accessible
const tab = this.tabs.findIndex(item => item.key == this.visibleTab); // use arrow function
console.log(tab);
},
next() {
}
}"
>
By using the arrow function item => item.key == this.visibleTab, the this keyword will correctly refer to the AlpineJS component, allowing you to access the visibleTab property.
1 like