Reon Low Yiyuan
Reon Low Yiyuan

Reputation: 153

How to update value AlpineJS

I have a button where I want it to add 1 to the amount of components whenever it is clicked. However, the displayed value did not change but when I type in the variable in the console, it is updated.

https://codepen.io/reonLOW/pen/ExyGyKb

    <div x-data="addItem()">
        <button @click="addItem()">+ 1</button>
        <br>
        <span x-text="amountOfComponents"></span>
        <br>
        <span x-text="itemPrice"></span>
    </div>
    var amountOfComponents = 0;
    var itemPrice = 0;

    const addItem = () => {

      amountOfComponents += 1;
      if (amountOfComponents <= 5) {
        itemPrice = 500 + (110 * amountOfComponents)
      } else if (amountOfComponents > 5, amountOfComponents <= 10) {
        itemPrice = 1000 + (105 * amountOfComponents)
      } else if (amountOfComponents > 10) {
        itemPrice = 1500 + (90 * amountOfComponents)
      }
      return {
        amountOfComponents,
        itemPrice
      }
    }

Also, how can I run it so that it shows 0 as the initial value? Pardon for my lack of knowledge in JavaScript.

Upvotes: 4

Views: 15477

Answers (1)

Shubham
Shubham

Reputation: 22349

As AlpineJs documentation states:

x-data declares a new component scope. It tells the framework to initialize a new component with the following data object.

So, when you when you're returning the modified values, it isn't getting reflected in the component object. Also, it's confusing and error-prone to have the same function init object and modify it.

The better approach is to follow AlpineJs component approach:

<div x-data="dropdown()">
    <button x-on:click="open">Open</button>

    <div x-show="isOpen()" x-on:click.away="close">
        // Dropdown
    </div>
</div>

<script>
    function dropdown() {
        return {
            show: false,
            open() { this.show = true },
            close() { this.show = false },
            isOpen() { return this.show === true },
        }
    }
</script>

Final code:

const items = () => {
  return {
    amountOfComponents: 0,
    itemPrice: 0,
    addItem: function () {
      this.amountOfComponents += 1;
      if (this.amountOfComponents <= 5) {
        this.itemPrice = 500 + (110 * this.amountOfComponents)
      } else if (this.amountOfComponents > 5, this.amountOfComponents <= 10) {
        this.itemPrice = 1000 + (105 * this.amountOfComponents)
      } else if (this.amountOfComponents > 10) {
        this.itemPrice = 1500 + (90 * this.amountOfComponents)
      }
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/2.7.3/alpine.js"></script>
<div x-data="items()">
        <button @click="addItem()">+ 1</button>
        <br>
        <span x-text="amountOfComponents"></span>
        <br>
        <span x-text="itemPrice"></span>
</div>

Upvotes: 9

Related Questions