Michal Karbownik
Michal Karbownik

Reputation: 1417

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

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>

Upvotes: 7

Views: 8815

Answers (2)

NICO
NICO

Reputation: 1843

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>

Upvotes: 1

Michal Karbownik
Michal Karbownik

Reputation: 1417

It is possible if you separate statements with a semicolon:

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

Upvotes: 16

Related Questions