当前位置:首页 > VUE

vue表格实现单选框

2026-01-12 06:08:16VUE

Vue 表格实现单选框的方法

在 Vue 中实现表格单选框功能,可以通过结合 el-table(Element UI)或原生表格与 Vue 的数据绑定特性完成。以下是几种常见实现方式:

使用 Element UI 的 el-table 组件

Element UI 提供了内置的单选框支持,可直接在表格中启用。

<template>
  <el-table
    :data="tableData"
    @selection-change="handleSelectionChange"
    style="width: 100%">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名">
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: '张三' },
        { name: '李四' }
      ],
      selectedRow: null
    };
  },
  methods: {
    handleSelectionChange(val) {
      this.selectedRow = val.length > 0 ? val[0] : null;
    }
  }
};
</script>

关键点:

vue表格实现单选框

  • 设置 type="selection" 启用复选框列。
  • 通过 @selection-change 监听选中变化,仅保留最后一项实现单选效果。

自定义单选框(原生或第三方库)

若需完全自定义单选框样式或逻辑,可通过手动绑定实现:

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

<script>
export default {
  data() {
    return {
      tableData: [
        { id: 1, name: '张三' },
        { id: 2, name: '李四' }
      ],
      selectedId: null
    };
  },
  methods: {
    handleRadioChange(item) {
      console.log('选中项:', item);
    }
  }
};
</script>

关键点:

vue表格实现单选框

  • 使用 v-model 绑定单选值(如 selectedId)。
  • 通过 @change 事件触发自定义逻辑。

使用 Vue 计算属性优化

若需动态禁用某些选项,可结合计算属性:

computed: {
  disabledItems() {
    return this.tableData.map(item => item.id === 2); // 禁用ID为2的项
  }
}

在模板中绑定 :disabled 属性:

<input
  type="radio"
  :disabled="disabledItems[index]">

注意事项

  1. 数据一致性:确保 v-model 绑定的值与选项的 value 属性匹配。
  2. 性能:大数据量时建议使用虚拟滚动(如 el-table 的虚拟滚动功能)。
  3. 样式:自定义单选框时可能需要隐藏原生输入框并用 CSS 美化。

通过以上方法,可灵活实现 Vue 表格中的单选功能,适应不同场景需求。

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

相关文章

css 制作表格

css 制作表格

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

vue表格实现复选框

vue表格实现复选框

Vue表格实现复选框的方法 基础实现(使用v-model绑定数组) 在Vue中可以通过v-model绑定数组来实现复选框功能。以下是一个基础示例: <template> <t…

h5实现单选框未勾选

h5实现单选框未勾选

实现单选框未勾选状态的方法 在HTML5中,单选框(<input type="radio">)默认未勾选。若需确保初始状态为未勾选或动态控制,可通过以下方式实现: 初始未勾选状态 直接…

vue实现表格透明

vue实现表格透明

实现表格透明的方法 在Vue中实现表格透明效果,可以通过CSS样式调整表格的背景透明度。以下是几种常见的方法: 设置表格背景透明度 通过CSS的background-color属性配合rgba…

vue实现拖拽表格

vue实现拖拽表格

Vue 实现拖拽表格的方法 使用第三方库(推荐) 推荐使用 vuedraggable 或 sortablejs 这类成熟的拖拽库,它们对 Vue 有良好支持且功能丰富。 安装 vuedraggab…

vue实现表格滚动

vue实现表格滚动

Vue 实现表格滚动的方法 使用 CSS 固定表头并滚动内容 通过 CSS 设置表格容器的固定高度和 overflow-y: auto,实现内容区域的滚动。表头部分使用 position: stick…