how to pass parameters in alpine js functions

Viewed 1329

I trying to pass variable tab in showTab in x-for my code look like this

<div x-data ="tabs">
<ul >

  <template x-for="tab in items">
      <li>
        <button @click="showtabs('tab')"></button>

        <button x-text= "tab" @click="tab.current = 'second'"></button>
      </li>
  </template>
</ul>
<div x-show='current'>
  fsfsdfds
</div>
<div x-show='current'>
  nice
</div>

in my script below I want to pass parameters in showtab()

document.addEventListener('alpine:init', () => {
Alpine.data('tabs', () => ({
    open: false,
    current: 'first',
    items: ['first', 'second'],
    showtabs(data_id){

      for(keys in items){
        var obj = items[keys]
        if(obj == data_id){

        }
      }
    }
}))

})

1 Answers

To pass a variable from template to function you can use Template literals and send `${expression}` for example:

<div x-data="tabs">
    <ul class="nav nav-tabs">
        <template x-for="tab in items">
            <li class="nav-item">
                <button @click="showTabs(`${tab}`)" x-text="tab"></button>
           </li>
        </template>
    </ul>
    <div x-show="current === 'first'">
        fsfsdfds
    </div>
    <div x-show="current === 'second'">
        nice
    </div>

    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('tabs', () => ({
                open: false,
                current: 'first',
                items: ['first', 'second'],
                showTabs(data_id) {
                    this.current = data_id;
                    }
            }))
        })
    </script>
Related