当前位置:首页 > VUE

vue实现表格多选效果

2026-02-24 03:24:18VUE

实现表格多选的基础方法

使用 Vue 的 v-model 绑定到复选框,结合 v-for 渲染表格数据。在数据中增加 selected 属性标记选中状态。

<template>
  <table>
    <thead>
      <tr>
        <th><input type="checkbox" v-model="selectAll"></th>
        <th>ID</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="item in tableData" :key="item.id">
        <td><input type="checkbox" v-model="item.selected"></td>
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { id: 1, name: 'Item 1', selected: false },
        { id: 2, name: 'Item 2', selected: false }
      ],
      selectAll: false
    }
  }
}
</script>

全选/反选功能实现

通过计算属性或监听器实现全选逻辑。当点击全选复选框时,同步所有行的选中状态。

vue实现表格多选效果

watch: {
  selectAll(newVal) {
    this.tableData.forEach(item => {
      item.selected = newVal
    })
  }
}

获取选中项数据

添加方法获取当前选中的数据,通过过滤 selectedtrue 的项。

vue实现表格多选效果

methods: {
  getSelectedItems() {
    return this.tableData.filter(item => item.selected)
  }
}

使用第三方组件库优化

Element UI 或 Ant Design Vue 等库提供现成的多选表格组件。

<!-- Element UI 示例 -->
<el-table
  :data="tableData"
  @selection-change="handleSelectionChange">
  <el-table-column type="selection" width="55"></el-table-column>
  <el-table-column prop="id" label="ID"></el-table-column>
</el-table>

<script>
export default {
  methods: {
    handleSelectionChange(val) {
      this.selectedItems = val
    }
  }
}
</script>

性能优化建议

对于大数据量表格,使用虚拟滚动或分页加载。避免直接绑定大量数据的响应式属性,可采用非响应式数据配合手动更新。

// 使用 Object.freeze 冻结非响应式数据
this.tableData = Object.freeze(largeDataArray)

标签: 多选表格
分享给朋友:

相关文章

css表格表单制作

css表格表单制作

CSS表格制作 使用CSS创建表格主要涉及<table>标签及其子元素的样式控制。以下是一个基础示例: <table class="styled-table"> <…

vue表格实现导出

vue表格实现导出

使用 vue-json-excel 插件 安装插件: npm install vue-json-excel --save 在组件中引入并注册: import JsonExcel from 'vue…

css表格的制作方法

css表格的制作方法

表格基础结构 使用HTML的<table>标签创建表格框架,搭配<tr>定义行,<td>定义单元格。例如: <table> <tr>…

vue实现多选下拉

vue实现多选下拉

Vue 实现多选下拉 使用 Vue 实现多选下拉可以通过原生 HTML <select> 元素结合 Vue 的双向绑定,或者使用第三方组件库如 Element UI、Vuetify 等。以…

vue实现表格滚动

vue实现表格滚动

Vue 实现表格滚动的方法 使用 CSS 固定表头并滚动内容 通过 CSS 设置表格容器的固定高度和 overflow-y: auto,实现内容区域的滚动。表头部分使用 position: stick…

vue实现复杂表格

vue实现复杂表格

Vue 实现复杂表格的方法 在 Vue 中实现复杂表格通常需要结合组件化、动态渲染和数据处理的能力。以下是几种常见的方法和实现技巧: 使用 Element UI 或 Ant Design Vue 的…