当前位置:首页 > 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>

全选/反选功能实现

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

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

获取选中项数据

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

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)

vue实现表格多选效果

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

相关文章

elementui多选

elementui多选

ElementUI 多选组件使用指南 ElementUI 提供了 el-select 组件支持多选功能,通过设置 multiple 属性即可启用。以下是具体实现方法和常见场景示例: 基础多选实现…

vue实现多选答题

vue实现多选答题

实现多选答题功能 在Vue中实现多选答题功能,可以通过以下方法完成: 数据准备 定义一个questions数组,每个问题包含题目和选项,选项是一个对象数组,每个选项有文本和是否被选中的状态。…

vue实现导出表格

vue实现导出表格

Vue 实现导出表格的方法 使用 xlsx 库导出 Excel 安装 xlsx 库 npm install xlsx 在 Vue 组件中引入 xlsx import * as XLSX fro…

vue动态表格实现

vue动态表格实现

Vue动态表格实现方法 使用v-for指令渲染动态数据 通过v-for指令可以循环遍历数组数据生成表格行,数据变化时表格自动更新。示例代码: <template> <table…

vue实现上传表格

vue实现上传表格

Vue实现上传表格的方法 使用Element UI上传组件 Element UI提供了el-upload组件,可以方便地实现文件上传功能。需要安装Element UI并引入相关组件。 安装Eleme…

vue实现合并表格

vue实现合并表格

vue实现合并表格的方法 使用Vue实现表格合并功能可以通过多种方式完成,常见方法包括自定义渲染、利用第三方库或手动处理数据。以下是几种典型实现方案: 使用Element UI的table组件实现…