服务器发送的数据是对象数组。我使用来遍历模板中的它们v-for
。
当用户单击增加和减少按钮时,我需要显示在一个范围内为每个项目选择的数量。我通过以下示例简化我的数据。该0
值是静态的。当用户单击按钮时,如何增加和减少每个项目的值?
let data = [
{type: 'car', color: 'white'
},{type: 'car', color: 'black'}
,.....]
<div v-for="(item, index) in data" :key="index">
<div>
{{item.color}}
<div class='btn-group'>
<button>increase</button>
<span>0</span> <----- how many selected
<button>decrease</button>
</div>
</div>
<div>
在这里,请检查此示例。
<template>
<div>
<div
v-for="(item, index) in records"
:key="index">
<div>
{{ item.color }}
<div class="btn-group">
<button @click="increase(index)">
+
</button>
<span>{{ item.val || 0 }}</span>
<button @click="decrease(index)">
-
</button>
</div>
</div>
<div />
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
records: [
{ type: 'car', color: 'white' },
{ type: 'car', color: 'black' },
],
};
},
created() {
this.fetchApi();
},
methods: {
fetchApi() {
axios.get('/your-url')
.then((response) => {
this.records = response.data.records.map((record) => {
return {
...record,
val: 0,
};
});
});
},
increase(index) {
this.records[index].val += 1;
},
decrease(index) {
this.records[index].val -= 1;
},
},
};
</script>
我希望这能够帮到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句