Vue2 iview 表格单元格 Input/Span 动态切换

想在Vue2项目中使用iview的表格组件,实现点击表格单元格时,在input和span之间动态切换吗?

按照以下步骤,即可轻松实现:

1. 安装和引入

确保已安装Vue2和iview,并在组件中正确引入Table和Input组件:

import { Table, Input } from 'iview';

export default {
  components: {
    Table,
    Input
  },
  // ...
};

2. 数据定义

在Vue组件的data中定义表格数据和状态:

data() {
  return {
    tableData: [
      // 表格数据
    ],
    editIndex: -1 // 当前编辑单元格索引,-1表示无编辑
  };
},

3. 表格模板

使用v-ifv-else指令根据editIndex切换显示input和span:

<template>
  <Table :columns='columns' :data='tableData'>
    <template slot-scope='{ row, column, $index }'>
      <span v-if='$index !== editIndex' @click='handleCellClick($index, column._index)'>{{ row[column.key] }}</span>
      <Input v-else v-model='tableData[Math.floor(editIndex / columns.length)][column.key]' @on-blur='handleCellBlur' />
    </template>
  </Table>
</template>

4. 事件处理

为每个单元格绑定点击事件,调用handleCellClick方法触发编辑状态,并处理失焦事件:

methods: {
  // 触发单元格编辑
  handleCellClick(rowIndex, columnIndex) {
    this.editIndex = rowIndex * this.columns.length + columnIndex;
  },
  // 结束单元格编辑
  handleCellBlur() {
    this.editIndex = -1;
  }
}

完成!

通过以上步骤,您就可以在Vue2中使用iview的表格组件,实现点击除表头外的任意单元格,自由切换input和span的功能了。请根据您的实际需求和项目的结构进行相应的修改和适配。


原文地址: https://www.cveoy.top/t/topic/oOS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录