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

高亮选中行样式

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

<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单选实现

Vue 单选实现 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定一个变量,可以实现单选效果。当用户选择不同的…

vue实现div单选

vue实现div单选

Vue 实现 div 单选 在 Vue 中实现 div 单选可以通过 v-model 结合 v-for 和事件绑定来完成。以下是具体实现方法: 模板部分 <template>…

css 制作表格

css 制作表格

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

css表格制作表格

css表格制作表格

CSS 表格制作方法 使用 CSS 创建表格可以通过多种方式实现,包括原生 HTML 表格元素结合 CSS 样式,或者使用纯 CSS 布局技术(如 Flexbox 或 Grid)模拟表格效果。以下是常…

vue实现导出表格

vue实现导出表格

Vue 中实现表格导出 使用 xlsx 库导出 Excel 安装 xlsx 库: npm install xlsx --save 在 Vue 组件中引入并使用: import XLSX fro…

css怎么制作表格

css怎么制作表格

使用HTML和CSS创建表格 HTML提供<table>标签用于创建表格结构,结合CSS可以自定义样式。以下是基本实现方法: HTML结构 <table> <th…