Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Property not accessible in AlpineJS

Hello,

I don't understand why the visibleTab is not accessible in the prev() function.

<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.indexOf(function (item) {
                return item.key == this.visibleTab; // not defined
            });
            console.log(tab);
        },
        next() {

        }
    }"
>

If you have any idea ;).

Thanks a lot.

V

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
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

Please or to participate in this conversation.