vue中table下面实现只有选中才能合计统计
时间: 2024-02-17 22:03:45 浏览: 52
在 Vue 中,实现只有选中 table 中的行才能进行合计统计可以通过以下步骤实现:
1. 在 table 中添加一个 checkbox 列,并使用 v-model 双向绑定选中状态。
2. 在底部合计统计区域,使用计算属性计算选中行的合计值。
具体的实现步骤如下:
```vue
<template>
<div>
<table>
<thead>
<tr>
<th>序号</th>
<th>名称</th>
<th>金额</th>
<th>选中</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="item.id">
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
<td>{{ item.amount }}</td>
<td><input type="checkbox" v-model="item.checked" /></td>
</tr>
</tbody>
</table>
<div v-if="hasSelected">
合计:{{ total }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: '商品1', amount: 100, checked: false },
{ id: 2, name: '商品2', amount: 200, checked: false },
{ id: 3, name: '商品3', amount: 300, checked: false },
],
};
},
computed: {
hasSelected() {
return this.list.some(item => item.checked);
},
total() {
return this.list.reduce((acc, item) => {
return item.checked ? acc + item.amount : acc;
}, 0);
},
},
};
</script>
```
在上面的代码中,我们在 table 中添加了一个 checkbox 列,并使用 v-model 双向绑定选中状态。然后,在底部合计统计区域,使用计算属性 hasSelected 判断是否有选中的行,如果有则计算选中行的合计值。需要注意的是,使用 reduce 方法计算合计值时需要判断当前行是否选中,只有选中才进行累加计算。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)