当前位置:首页 > VUE

vue 实现表格单选

2026-03-28 06:33:21VUE

Vue 实现表格单选的方法

使用 v-model 绑定选中项

通过 v-model 绑定一个变量来记录当前选中的行数据。在表格的每一行添加单选按钮或点击事件来更新这个变量。

vue 实现表格单选

<template>
  <table>
    <tr v-for="item in tableData" :key="item.id" @click="selectedRow = item">
      <td><input type="radio" :checked="selectedRow === item"></td>
      <td>{{ item.name }}</td>
    </tr>
  </table>
</template>

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

使用计算属性优化

添加计算属性来判断当前行是否被选中,使模板更简洁。

vue 实现表格单选

<template>
  <table>
    <tr v-for="item in tableData" :key="item.id" @click="selectedRow = item" 
        :class="{ 'selected': isSelected(item) }">
      <td><input type="radio" :checked="isSelected(item)"></td>
      <td>{{ item.name }}</td>
    </tr>
  </table>
</template>

<script>
export default {
  computed: {
    isSelected() {
      return (item) => this.selectedRow === item
    }
  }
}
</script>

使用第三方组件库

若使用 Element UI 等组件库,可直接利用其提供的单选表格功能。

<template>
  <el-table
    :data="tableData"
    @current-change="handleCurrentChange"
    highlight-current-row>
    <el-table-column prop="name" label="Name"></el-table-column>
  </el-table>
</template>

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

添加样式反馈

为选中行添加视觉反馈,提升用户体验。

.selected {
  background-color: #f0f0f0;
}

tr:hover {
  cursor: pointer;
}

注意事项

  • 确保每个数据项有唯一标识符(如 id)
  • 考虑添加初始选中状态逻辑
  • 移动端适配可能需要调整点击区域大小
  • 大型表格需考虑性能优化

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

相关文章

css好看的表格制作

css好看的表格制作

CSS表格美化方法 边框与间距优化 使用border-collapse合并边框,避免双线边框。设置padding增加单元格内边距,提升可读性。 table { border-collapse:…

vue实现表格数据修改

vue实现表格数据修改

实现表格数据修改的基本思路 在Vue中实现表格数据修改通常涉及以下核心步骤:数据绑定、编辑状态切换、表单输入处理和数据提交。以下是一个典型实现方案: 数据绑定与渲染 使用v-for指令循环渲染表格数…

vue实现动态用户表格

vue实现动态用户表格

Vue 动态用户表格实现方法 基础表格结构 使用<table>或第三方组件库(如Element UI的el-table)构建基础框架。静态数据示例: <template>…

vue实现表格拖动列宽

vue实现表格拖动列宽

实现表格列宽拖动的核心思路 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽逻辑,动态修改列宽。需要处理表头与表体的联动,确保拖动时视觉一致。 基础HTML结构 &…

css好看的表格制作

css好看的表格制作

使用CSS制作美观表格的方法 边框与间距优化 通过border-collapse属性合并边框,避免双边框效果。设置padding增加单元格内边距,提升可读性。 table { border-…

css表格制作表格

css表格制作表格

CSS 表格制作方法 基础表格结构 使用HTML的<table>标签创建表格框架,搭配<tr>(行)、<td>(单元格)和<th>(表头)标签: &l…