Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue可编辑表格

作者:酷帥男爵   发布日期:2026-04-19   浏览:96

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="(header, index) in headers" :key="index">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
          <td v-for="(cell, cellIndex) in row" :key="cellIndex">
            <input
              v-if="editingCell === `${rowIndex}-${cellIndex}`"
              v-model="tableData[rowIndex][cellIndex]"
              @blur="editingCell = null"
              @keyup.enter="editingCell = null"
            />
            <span v-else @dblclick="editCell(rowIndex, cellIndex)">
              {{ cell }}
            </span>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      headers: ["Name", "Age", "City"],
      tableData: [
        ["Alice", 24, "New York"],
        ["Bob", 30, "San Francisco"],
        ["Charlie", 28, "Los Angeles"]
      ],
      editingCell: null
    };
  },
  methods: {
    editCell(row, cell) {
      this.editingCell = `${row}-${cell}`;
    }
  }
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
}

th {
  background-color: #f2f2f2;
}
</style>

解释说明

  1. 模板部分 (<template>):

    • 使用了一个简单的 HTML 表格结构,包含表头 (<thead>) 和表格主体 (<tbody>)。
    • 表头通过 v-for 指令动态生成。
    • 表格主体中的每一行和每一列也通过 v-for 动态生成。每个单元格可以是可编辑的输入框或静态文本。
  2. 脚本部分 (<script>):

    • 定义了 headers 数组来存储表头信息。
    • tableData 是一个二维数组,存储表格的数据。
    • editingCell 变量用于跟踪当前正在编辑的单元格的位置。
    • editCell 方法用于切换单元格的编辑状态。
  3. 样式部分 (<style scoped>):

    • 提供了一些基本的样式,使表格看起来更美观。

这个示例展示了如何使用 Vue.js 创建一个简单的可编辑表格。用户可以通过双击单元格进入编辑模式,并在编辑完成后自动保存更改。

上一篇:vue自定义事件

下一篇:vue表单校验

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站