vue怎么实现表格多选行数据
时间: 2024-05-07 12:18:13 浏览: 16
在 Vue 中实现表格的多选行数据,一般有两种方式:
1. 使用 Checkbox 实现:在每一行数据前添加一个 Checkbox,然后将选中的行的数据存储到一个数组中。具体实现可以参考以下代码:
```html
<template>
<div>
<table>
<thead>
<tr>
<th>
<input type="checkbox" v-model="allChecked" @change="checkAll" />
</th>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="item.id">
<td>
<input type="checkbox" v-model="checkedList" :value="item" />
</td>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: "Tom", age: 18 },
{ id: 2, name: "Jerry", age: 20 },
{ id: 3, name: "Mike", age: 22 }
],
checkedList: [],
allChecked: false
};
},
methods: {
checkAll() {
if (this.allChecked) {
this.checkedList = [...this.list];
} else {
this.checkedList = [];
}
}
}
};
</script>
```
2. 使用表格的 row-click 事件实现:在表格中添加一个 row-click 事件,当用户选中某一行时,将该行的数据存储到一个数组中。具体实现可以参考以下代码:
```html
<template>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="item.id" @click="handleClick(item)">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: "Tom", age: 18 },
{ id: 2, name: "Jerry", age: 20 },
{ id: 3, name: "Mike", age: 22 }
],
checkedList: []
};
},
methods: {
handleClick(item) {
const index = this.checkedList.findIndex(i => i.id === item.id);
if (index > -1) {
this.checkedList.splice(index, 1);
} else {
this.checkedList.push(item);
}
}
}
};
</script>
```
这两种方式都可以实现表格的多选行数据,具体选择哪种方式可以根据实际情况进行选择。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)