How to execute multiple statements within a single Alpine.js attribute?

Viewed 2341

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>
2 Answers

It is possible if you separate statements with a semicolon:

<button x-data 
        @click="alert('first'); alert('second')">
  Click me
</button>

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>
Related