可编辑表格实现

331 阅读1分钟

需求为当前的一整行,除了kpi,其他的在鼠标划过时出现可编辑标签,可对当前文案进行编辑,如下所示: 截屏2022-09-20 上午9.38.53.png

截屏2022-09-20 上午9.41.29.png

<el-table
    :data="tableData.tableItemData"
    border
    max-height="500px"
    @cell-mouse-enter="tableHover"
    @cell-mouse-leave="hoverLeave"
    >
    <el-table-column
        v-for="(column, index) in tableData.columns"
        :key="`${column.prop}_${index}`"
        :label="column.label"
        :resizable="false"
        :prop="column.prop"
        :min-width="column.minWidth || 120"
    >
        <template #default="scope">
            <template v-if="column.prop !== 'catalogName' && tableData.editItem" class="wrap">
                <el-input v-if="scope.row[column.prop+'_copy'] || scope.row[column.prop+'_copy'] == ''" :ref="addRef" v-model="scope.row[column.prop+'_copy']" placeholder="请输入数字" size="mini" @blur="inputBlur(scope.row,column)"/>
                <span v-else><span>{{ scope.row[column.prop] }}</span><i class="iconfont bbx-icon-bianji1" @click="modify(scope.row, column)"></i></span>
            </template>
            <template v-else>
                {{ scope.row[`${column.prop}`] }}
            </template>
        </template>
    </el-table-column>
</el-table>
<script>
export default {
    props: {
        tableData: {
            type: Object,
            default: ()=> ({})
        }
    },
    data() {
        return {
            currentRef:null,
        };
    },
    methods: {
        tableHover(row, column, cell) {
            // catalogName是可编辑的那一行,如果是的话就给当前的单元格加上类名,其他的给return掉,不加类名
            if(row.catalogName !== this.tableData.editItem) return 
            cell.classList.add('myclass')
        },
        hoverLeave(row, column, cell, event) {
            // 离开单元格的时候类名去除,编辑按钮隐藏
            cell.classList.remove('myclass')
        },
        // 失去焦点初始化
        async inputBlur(row, column) {
            let value = row[`${column.prop}_copy`]
            if(校验成功) {
                // 校验成功操作
                row[column.prop] = value || row[column.prop]
                row[`${column.prop}_copy`] = null
            }else {
                //校验失败当前input不失焦
            }
        },
        modify(row, column) {
            row[`${column.prop}_copy`] = row[column.prop]
            this.$nextTick(()=>{
                this.currentRef?.focus()
            })
        },
        addRef(e){
            this.currentRef = e
        }
        
    },
};
</script>
<style lang="scss" scoped>
.bbx-icon-bianji1 {
    display: none;
}
.myclass .bbx-icon-bianji1 {
    display: inline-block;
}
.myclass .bbx-icon-bianji1:hover{
    color: #13c2c2;
}
.myclass {
    position: relative;
    i {
        position: absolute;
        right: 12px;
    }
}
</style>