Reo*_*uan 4 html javascript alpine.js
我有一个按钮,我希望它在单击时将组件数量加 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>
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我怎样才能运行它,使其显示 0 作为初始值?请原谅我缺乏 JavaScript 知识。
正如 AlpineJs 文档所述:
x-data 声明一个新的组件范围。它告诉框架使用以下数据对象初始化新组件。
因此,当您返回修改后的值时,它不会反映在组件对象中。此外,使用相同的函数初始化对象并修改它是令人困惑和容易出错的。
更好的方法是遵循 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>
Run Code Online (Sandbox Code Playgroud)
最终代码:
<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>
Run Code Online (Sandbox Code Playgroud)
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)
}
}
}
}Run Code Online (Sandbox Code Playgroud)