6

I would like to execute multiple statements within a single Alpine.js event handler (however, I believe it could be generalized to any attribute).

An example of what I would like to achieve:

<button x-data 
        @click="alert('first')" 
        @click="alert('second')">
  Click me
</button>
Michal Karbownik
  • 1,138
  • 14
  • 28

2 Answers2

12

It is possible if you separate statements with a semicolon:

<button x-data 
        @click="alert('first'); alert('second')">
  Click me
</button>
Michal Karbownik
  • 1,138
  • 14
  • 28
1

You could extract your component logic and add a handle for the click event.

<div x-data="myComponent">
  <button x-on:click.prevent="handleClick">Click me</button>
</div>

<script>
  const myComponent = () => {
  return {
    handleClick() {
      console.log('First event')
      console.log('Second event')
    }
  }
}
</script>
NICO
  • 1,695
  • 1
  • 12
  • 11