当前位置:首页 > 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)
  • 考虑添加初始选中状态逻辑
  • 移动端适配可能需要调整点击区域大小
  • 大型表格需考虑性能优化

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

相关文章

vue表格实现复选框

vue表格实现复选框

vue表格实现复选框 在Vue中实现表格复选框功能,可以通过以下方法完成: 方法一:使用el-table(Element UI) 安装Element UI后,在表格列中直接添加type="sele…

vue实现 单选

vue实现 单选

实现 Vue 单选功能 在 Vue 中实现单选功能可以通过多种方式完成,常见的有使用原生 HTML 的 <input type="radio"> 结合 Vue 的数据绑定,或使用第三方 U…

css表格制作

css表格制作

CSS表格制作方法 使用CSS创建表格可以通过多种方式实现,以下是常见的几种方法: 使用HTML原生表格标签结合CSS样式 <table class="styled-table">…

css制作表格

css制作表格

CSS 制作表格的方法 使用 CSS 可以灵活地创建和样式化表格,以下是几种常见的方法: 使用 HTML 表格标签结合 CSS 样式 通过 HTML 的 <table>、<tr&g…

vue怎么实现单选

vue怎么实现单选

实现单选功能的方法 在Vue中实现单选功能可以通过多种方式,以下是几种常见的实现方法: 使用原生HTML单选按钮 通过v-model绑定数据,结合原生<input type="radi…

vue实现上传表格

vue实现上传表格

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