Javascript 如何更新AlpineJS的值

Javascript 如何更新AlpineJS的值,javascript,html,alpine.js,Javascript,Html,Alpine.js,我有一个按钮,我希望它添加1到数量的组成部分,每当它被点击。但是,显示的值没有改变,但当我在控制台中键入变量时,它会被更新 + 1 var amountOfComponents=0; var itemPrice=0; 常量附加项=()=>{ amountOfComponents+=1; if(组件数量5,组件数量10){ itemPrice=1500+(90*amountOfComponents) } 返回{ 组件数量, 项目价格 } } 另外,如何运行它,使其显示0作为初始值? 请

我有一个按钮,我希望它添加1到数量的组成部分,每当它被点击。但是,显示的值没有改变,但当我在控制台中键入变量时,它会被更新


+ 1


var amountOfComponents=0;
var itemPrice=0;
常量附加项=()=>{
amountOfComponents+=1;
if(组件数量5,组件数量10){
itemPrice=1500+(90*amountOfComponents)
}
返回{
组件数量,
项目价格
}
}
另外,如何运行它,使其显示0作为初始值?
请原谅我缺乏JavaScript知识。

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

打开
//下拉列表
函数下拉列表(){
返回{
秀:假,,
open(){this.show=true},
close(){this.show=false},
isOpen(){返回this.show==true},
}
}
最终代码:

const items=()=>{
返回{
组件数量:0,
项目价格:0,
附加项:函数(){
此值为.amountOfComponents+=1;
if(this.amountOfComponents 5,this.amountOfComponents 10){
this.itemPrice=1500+(90*this.amountOfComponents)
}
}
}
}

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

打开
//下拉列表
函数下拉列表(){
返回{
秀:假,,
open(){this.show=true},
close(){this.show=false},
isOpen(){返回this.show==true},
}
}
最终代码:

const items=()=>{
返回{
组件数量:0,
项目价格:0,
附加项:函数(){
此值为.amountOfComponents+=1;
if(this.amountOfComponents 5,this.amountOfComponents 10){
this.itemPrice=1500+(90*this.amountOfComponents)
}
}
}
}

+ 1



如何在嵌套的x-data中使用它?如何在嵌套的x-data中使用它?
<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>