- 使用
el-table
和el-table-column
创建表格。 - 在单元格的默认插槽中,使用
div
显示文本内容,单击时触发编辑功能。 - 使用
el-input
组件在单元格中显示编辑框。 data()
方法中定义了tableData,
tabClickIndex: null,tabClickLabel: '',用于判断是否处于编辑转态- @cell-click="tabClick" 方法用于将单元格设置为编辑状态,并使用
this.$nextTick
来确保输入框能获得焦点。 - 通过blur监听失去焦点。
javascript"><template><div><el-table :data="dataDetail" :row-class-name="tableRowClassName" border style="width: 100%" max-height="500px" @cell-click="tabClick"><el-table-column prop="test1" label="test1" align="center"><template slot-scope="scope"><span v-if="scope.row.index === tabClickIndex && tabClickLabel === 'test1'"><el-input :ref="'test1'+scope.row.id" v-model="scope.row.test1" maxlength="300" placeholder="请输入test1" size="mini" @blur="inputBlur" /></span><span v-else>{{ scope.row.test1 }}</span></template></el-table-column><el-table-column prop="test2" label="test2" width="120px" align="center"><template slot-scope="scope"><span v-if="scope.row.index === tabClickIndex && tabClickLabel === 'test2'"><el-input :ref="'test2'+scope.row.id" v-model="scope.row.test2" :blur="inputBlur" placeholder="请输入test2" size="mini" @blur="inputBlur" /></span><span v-else>{{ scope.row.test2 | fmoney }}</span></template></el-table-column><el-table-column prop="test3" label="test3" align="center" width="180"><template slot-scope="scope"><span v-if="scope.row.index === tabClickIndex && tabClickLabel === 'test3'"><el-input :ref="'test3'+scope.row.id" v-model="scope.row.test3" maxlength="300" placeholder="请输入test3" size="mini" @blur="inputBlur" /></span><span v-else>{{ scope.row.test3 }}</span></template></el-table-column></el-table></div></template><script>
export default {data () {return {tabClickIndex: null, // 点击的单元格tabClickLabel: '', // 当前点击的列名dataDetail: [{ id: '123', test1: 'sss' }, { id: '456', test1: 'sss' }]}},methods: {tableRowClassName ({ row, rowIndex }) {row.index = rowIndex},tabClick (row, column, cell, event) {switch (column.label) {case 'test1':this.tabClickIndex = row.indexthis.tabClickLabel = column.labelbreakcase 'test2':this.tabClickIndex = row.indexthis.tabClickLabel = column.labelbreakcase 'test3':this.tabClickIndex = row.indexthis.tabClickLabel = column.labelbreakdefault: return}const key = this.tabClickLabel + row.idthis.$nextTick(() => {this.$refs[key].focus()})},inputBlur (row, event, column) {this.tabClickIndex = nullthis.tabClickLabel = ''},}
}
</script><style>
</style>