Table of Contents & Menu
On this page
Navigation

Property Mutation in Alpine CSP

Direct property mutations within Alpine attributes, like @click="open = !open", are not allowed in Alpine CSP.

<button type="button" @click="open = !open">Toggle</button>

Instead, encapsulate the mutation logic within a method:

<button type="button" @click="toggle">Toggle</button>
  toggle() {
    this.open = ! this.open;
  }

Tip

For reducing boilerplate with boolean toggles, see hyva.createBooleanObject.

Passing Arguments

Directly passing arguments to methods from Alpine attributes is not supported in Alpine CSP. Use data attributes to pass values instead.

<button @click="selectItem" data-item-id="<?= (int) $item->getId() ?>">
    Select
</button>
  selectItem() {
    this.selected = this.$el.dataset.itemId;
  }

Alpine variables like $event and x-for iteration variables (e.g., item) are accessible as properties of this within methods.

<template x-for="item in items">
    <input @click.prevent="processClick"/>
</template>
processClick() {
    const value = this.$event.target.value;
    if (value === this.item.id) { // item is the x-for iteration variable
        // do something
    }
}