如何增加状态项中的值?
How to increment a value in state item?
我有一个显示所有项目的视图,我想通过单击添加按钮来增加每个项目的数量。我在设置时遇到了问题 - 这是我到目前为止的想法。
items: [{
id: 1,
name: "Car",
quantity: 1
},
{
id: 2,
name: "Car2",
quantity: 1
},
]
我遇到的突变 -> 如何在此处定位数组中的特定项目?
increment(state) {
state.items.quantity++
}
html
<div v-for="item in items" :key="item.id">
<div>
{{item.name}}
{{item.quantity}}
<button @click="add()">+</button>
</div>
html
中的方法
add() {
this.store.commit("increment")
}
将 id 传递给方法并传递给突变:
<button @click="add(item.id)">+</button>
add(id) {
this.$store.commit("increment", id)
}
准备您的变异以接收 id,然后查找并增加数量
increment(state, id) {
const item = state.items.find(i => i.id === id);
item.quantity++;
}
我有一个显示所有项目的视图,我想通过单击添加按钮来增加每个项目的数量。我在设置时遇到了问题 - 这是我到目前为止的想法。
items: [{
id: 1,
name: "Car",
quantity: 1
},
{
id: 2,
name: "Car2",
quantity: 1
},
]
我遇到的突变 -> 如何在此处定位数组中的特定项目?
increment(state) {
state.items.quantity++
}
html
<div v-for="item in items" :key="item.id">
<div>
{{item.name}}
{{item.quantity}}
<button @click="add()">+</button>
</div>
html
中的方法 add() {
this.store.commit("increment")
}
将 id 传递给方法并传递给突变:
<button @click="add(item.id)">+</button>
add(id) {
this.$store.commit("increment", id)
}
准备您的变异以接收 id,然后查找并增加数量
increment(state, id) {
const item = state.items.find(i => i.id === id);
item.quantity++;
}