当前位置:首页 > VUE

vue表格实现单选

2026-03-28 19:35:17VUE

实现 Vue 表格单选功能

在 Vue 中实现表格单选功能可以通过以下方法完成,核心思路是绑定选中状态并监听用户操作。

方法一:使用 v-model 绑定选中行

通过 v-model 绑定一个变量存储当前选中行的数据,结合 @click 事件切换选中状态。

<template>
  <table>
    <tr v-for="(item, index) in tableData" :key="index" 
        @click="selectedRow = item"
        :class="{ 'selected': selectedRow === item }">
      <td>{{ item.name }}</td>
      <td>{{ item.age }}</td>
    </tr>
  </table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: 'Alice', age: 25 },
        { name: 'Bob', age: 30 }
      ],
      selectedRow: null
    };
  }
};
</script>

<style>
.selected {
  background-color: #f0f0f0;
}
</style>

方法二:使用计算属性动态判断选中状态

通过计算属性或方法判断当前行是否为选中状态,适用于需要复杂逻辑的场景。

<template>
  <table>
    <tr v-for="(item, index) in tableData" :key="index" 
        @click="selectRow(item)"
        :class="{ 'selected': isSelected(item) }">
      <td>{{ item.name }}</td>
      <td>{{ item.age }}</td>
    </tr>
  </table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: 'Alice', age: 25 },
        { name: 'Bob', age: 30 }
      ],
      selectedRow: null
    };
  },
  methods: {
    selectRow(item) {
      this.selectedRow = item;
    },
    isSelected(item) {
      return this.selectedRow === item;
    }
  }
};
</script>

方法三:结合第三方表格组件(如 Element UI)

如果使用 Element UI 的 el-table 组件,可以直接利用其内置的单选功能。

vue表格实现单选

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

<script>
export default {
  data() {
    return {
      tableData: [
        { name: 'Alice', age: 25 },
        { name: 'Bob', age: 30 }
      ]
    };
  },
  methods: {
    handleCurrentChange(val) {
      console.log('当前选中行:', val);
    }
  }
};
</script>

关键点说明

  • 数据绑定:通过 selectedRow 变量存储当前选中行的数据。
  • 样式反馈:通过 CSS 类名(如 .selected)或组件内置属性(如 highlight-current-row)高亮选中行。
  • 事件监听:使用 @click@current-change 监听用户操作并更新选中状态。

以上方法均能实现表格单选功能,可根据项目需求选择原生实现或结合第三方组件库。

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

相关文章

vue实现表格拖动列宽

vue实现表格拖动列宽

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

vue 实现单选

vue 实现单选

实现单选功能的方法 在Vue中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用v-model绑定单选按钮 通过v-model可以轻松实现单选功能。将v-model绑定到一个变量,单选…

vue 实现表格单选

vue 实现表格单选

实现表格单选的基本思路 在Vue中实现表格单选功能,通常需要结合表格组件(如el-table)和数据绑定。核心逻辑是通过点击事件更新当前选中行的唯一标识(如id),并通过:class或:style绑定…

vue实现单选按钮

vue实现单选按钮

实现单选按钮的基本方法 在Vue中实现单选按钮通常使用v-model指令绑定数据,结合input元素的type="radio"属性。以下是一个基础示例: <template> <…

vue实现单选弹窗

vue实现单选弹窗

Vue 实现单选弹窗的方法 使用 Element UI 的 Dialog 和 Radio 组件 安装 Element UI 后,可以通过 Dialog 和 Radio 组件快速实现单选弹窗功能。 &…

css表格的制作方法

css表格的制作方法

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