当前位置:首页 > VUE

vue表格实现单选

2026-01-15 06:06:03VUE

实现 Vue 表格单选功能

使用 v-model 绑定选中状态

在表格的每一行添加单选按钮或点击行触发选中,通过 v-model 绑定一个变量存储当前选中行的唯一标识(如 id)。
示例代码:

vue表格实现单选

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

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

高亮选中行样式

通过动态类名或样式绑定,为选中行添加视觉反馈。
示例:

vue表格实现单选

<tr 
  v-for="item in tableData" 
  :key="item.id" 
  @click="selectedId = item.id"
  :class="{ 'active-row': selectedId === item.id }"
>

使用第三方表格组件(如 Element UI)

若使用 Element UI 的 el-table,可通过 highlight-current-row 属性实现单选高亮:

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

<script>
export default {
  methods: {
    handleCurrentChange(val) {
      this.selectedRow = val; // val 为当前选中行数据
    }
  }
};
</script>

注意事项

  • 确保每行数据有唯一标识(如 id),用于区分选中状态。
  • 若需默认选中某一行,可在 data 中初始化 selectedIdselectedRow
  • 避免直接操作 DOM,优先通过 Vue 的数据驱动方式更新状态。

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

相关文章

vue表格实现教学

vue表格实现教学

基础表格实现 使用 Vue 的 v-for 指令渲染数组数据到表格中。 <template> <table> <thead> <…

vue 实现组单选

vue 实现组单选

Vue 实现单选组 在 Vue 中实现单选组可以通过多种方式,以下是几种常见的实现方法: 使用 v-model 绑定单选按钮组 通过 v-model 绑定一个变量,单选按钮的 value 属性对应…

vue实现表格刷新

vue实现表格刷新

Vue 实现表格刷新的方法 使用 v-if 强制重新渲染 通过 v-if 控制表格的显示与隐藏,切换时 Vue 会重新渲染组件。 <template> <button @cli…

vue实现表格输出

vue实现表格输出

Vue 实现表格输出的方法 使用原生表格标签 在 Vue 模板中可以直接使用 HTML 原生表格标签(<table>、<tr>、<td>等)渲染数据。通过 v-fo…

vue实现全选 单选

vue实现全选 单选

Vue实现全选与单选功能 在Vue中实现全选和单选功能通常涉及数据绑定、事件处理和计算属性的使用。以下是两种常见的实现方式: 基于数组的复选框实现 <template> <…

vue 实现表格分页

vue 实现表格分页

Vue 实现表格分页的方法 使用 Element UI 的分页组件 Element UI 提供了现成的分页组件 el-pagination,结合 el-table 可以快速实现表格分页功能。 安装…