gpt4 book ai didi

javascript - 如何更新值AlpineJS

转载 作者:行者123 更新时间:2023-12-01 23:42:33 25 4
gpt4 key购买 nike

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

因此,当您返回修改后的值时,它不会反射(reflect)在组件对象中。此外,拥有相同的函数 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>

关于javascript - 如何更新值AlpineJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64797708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com