如何更新值AlpineJS

How to update value AlpineJS

我有一个按钮,我希望它在单击时将组件数量加 1。然而,显示的值并没有改变,但是当我在控制台中输入变量时,它被更新了。

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

另外,我怎样才能运行它显示0作为初始值? 请原谅我在 JavaScript.

方面缺乏知识

正如 AlpineJs 文档所述:

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

因此,当您返回修改后的值时,它不会反映在组件对象中。另外,具有相同的函数初始化对象并对其进行修改是令人困惑和容易出错的。

更好的方法是遵循 AlpineJs 组件方法:

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

最终代码:

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>