Как найти общее количество товаров?
У меня есть задача: Найти общее количество товаров. Само количество я задаю на стороне клиента (input type=number). В самих данных никакого поля для количества нет. Мне нужно просто динамически выводить общее количество товаров при любом изменении input.
Как это реализовать в моем коде на Vue ? Вот что сейчас есть:
Главный компонент App.vue
<template>
<mainTable
:table_data="items"
></mainTable>
</template>
<script>
import axios from 'axios';
import mainTable from './components/main-table'
export default {
name: 'App',
components: {
mainTable
},
data() {
return {
items: null,
}
},
methods: {},
mounted() {
axios
.get('http://localhost:3000/items')
.then(response => (this.items = response.data))
.catch(error => console.log(error));
},
}
</script>
Компонент mainTable. Здесь шапка моей таблицы, а ряды ренерятся с помощью другого компонента: tableRow.
mainTalbe
<template>
<div class="main-table">
<table class="table">
<thead class="table-header">
<th>Цена</th>
<th>Количество</th>
<th>Скидка %</th>
<th>Итого</th>
</thead>
<TableRow
v-for="row in table_data" :key="row.id"
:row_data = "row" :onCount='onCount'>
</TableRow>
<tbody>
</tbody>
<p>Общее количество </p>
</table>
</div>
</template>
<script>
import TableRow from './table-row';
export default {
name: "main-table",
components: {
TableRow
},
props: {
table_data: {
type: Array,
default: () => {
return [];
}
},
},
computed: {},
data() {
return {
}
},
methods: {
onCount(data) {
console.log(data)
}
}
}
</script>
И компонент tableRow
<template>
<tr class="table-row">
<td>
<input type="number" min="0"
v-model="price" id="item-price">
</td>
<td>
<input type="number" id="item-count" min="0" v-model.number="count">
</td>
<td>
<input type="number" min="0" id="item-sale"
v-model="percent">
</td>
<td>
{{ totalStr }}
</td>
<td>
<button @click="sendCount()">{{ this.row_data.id }}
</button>
</td>
</tr>
</template>
<script>
export default {
name: 'tableRow',
props: {
row_data: {
type: Object,
default: () => {
return {};
}
},
onCount : {}
},
data() {
return {
price: this.row_data.price,
percent: this.row_data.sale,
count_: this.row_data.count,
get count() { return this.count_ > 0 ? this.count_: ""; },
set count(v) { return this.count_ = Math.max(Math.min(v, 500), 0); },
}
},
methods: {
sendCount() {
this.onCount({ id: this.row_data.id, count: this.count});
},
},
computed: {
total() {
return this.row_data.price * this.count * (1.0-this.percent*0.01);
},
totalStr() {
return this.total>0 ? this.total.toFixed(2) : ""; // toFixed возвращает строку
}
},
}
</script>
<style>
input {
font-size: 18px;
}
#item-price {
width: 50px;
text-align: center;
border: 0;
}
#item-sale {
width: 50px;
border: 0;
}
#item-count {
width: 50px;
border: 1px solid lightgrey;
box-shadow: none;
}
</style>