【问题标题】:How to update value AlpineJS如何更新值 AlpineJS
【发布时间】:2020-11-12 12:33:42
【问题描述】:

我有一个按钮,我希望它在单击时将组件数量加 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 知识。

【问题讨论】:

    标签: javascript html alpine.js


    【解决方案1】:

    正如 AlpineJs 文档所述:

    x-data 声明了一个新的组件范围。它告诉框架使用以下数据对象初始化一个新组件。

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

    更好的方法是遵循 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>

    【讨论】:

    • 如何在嵌套的 x 数据中使用它?
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2021-06-06
    • 2021-07-18
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多