二次封装el-table表格根据类名不同切换样式

同一个表格,加类名切换不同风格

 定义theme变量 ,并绑定在标签上

在style里面定义样式,表格的字体颜色为白色  现在添加一个名为theme的类名 类控制他的样式修改

 样式代码如下:

 &[theme='one'] {
        :deep(.el-table) {
            color: red;
        }
    }

 三 使用 

在对应页面上使用的table标签上 加上自定义的类名

 效果如下:

 

 封装表格代码 新建MyTable文件夹 index.vue文件和getValue.ts文件

index.vue文件如下


<template>
    <article ref="container" height="720px" :theme="theme">
        <el-table
            ref="table"
            class="table"
            :data="tableData"
            :max-height="maxHeight"
            @selection-change="selectChange"
            :highlight-current-row="curSelect"
            @current-change="currentChange"
            :row-key="rowKey"
            :indent="24"
            :default-expand-all="expandAll"
            @row-contextmenu="clearCur"
            @contextmenu.prevent="() => {}"
            :header-cell-style="{ background: '#0B3357' }"
            :row-class-name="tableRowClassName"
        >
            <slot name="expand"></slot>
            <el-table-column v-if="select" type="selection" />
            <el-table-column v-for="item in tableHead" :prop="item.prop" :label="item.label ? item.label : item.prop" :align="align" :min-width="100" show-overflow-tooltip>
                <template #default="scope">
                    <el-table-column v-if="item.children" show-overflow-tooltip v-for="child in item.children" :prop="item.prop + '.' + child.prop" :label="child.label ? child.label : child.prop" :align="align">
                        <template #default="scope">
                            <span v-html="getValue(getValue(scope.row, item.prop), child.prop)"></span>
                        </template>
                    </el-table-column>
                    <span v-html="getValue(scope.row, item.prop)"></span>
                </template>
            </el-table-column>
            <slot> </slot>
        </el-table>
    </article>
</template>

<script setup lang="ts">
// @ts-ignore
// import { Vue3JsonExcel } from "vue3-json-excel"
import { ref, nextTick } from 'vue';

import * as XLSX from 'xlsx';
// @ts-ignore
import FileSaver from 'file-saver';

import getValue from './getValue';
import { reqGetAlarmSum } from '@/api';
// 设置表格高度
const container = ref();
const maxHeight = ref();
nextTick(() => {
    const h = container.value.offsetHeight;
    maxHeight.value = h ? h : 700;

    // 监听容器大小变化
    const resizeObserver = new ResizeObserver(entries => {
        // 重新设置最大高度
        maxHeight.value = container.value.offsetHeight;
    });
    resizeObserver.observe(container.value);
});

// 字段成员类型
type tableHeadItem = {
    prop: string;
    label: string;
    children?: Array<tableHeadItem>;
};
const props = defineProps({
    // 字段
    tableHead: {
        type: Array as () => Array<tableHeadItem>,
        required: true,
    },
    // 数据
    tableData: {
        type: Array,
        required: true,
    },
    // 是否需要选中框
    select: {
        type: Boolean,
        default: false,
    },
    // 多选择事件
    selectChange: {
        type: Function as (...args: any[]) => any,
        default: () => {},
    },
    // 是否可以选择
    curSelect: {
        type: Boolean,
        default: false,
    },
    // 单选事件
    currentChange: {
        type: Function as (...args: any[]) => any,
        default: () => {},
    },
         // 主题
         theme: {
        type: String,
        default: '',
    },
    // 是否需要边框
    border: {
        type: Boolean,
        default: true,
    },
    // 树形数据 key
    rowKey: {
        type: String,
        default: 'id',
    },
    // 树形数据是否全部展开
    expandAll: {
        type: Boolean,
        default: false,
    },

    // 表格对齐放 align
    align: {
        type: String,
        default: 'center',
    },

});
const table = ref();
const clearCur = () => {
    // 取消选中
    if (props.curSelect) {
        table.value.setCurrentRow();
    }
};

// 生成导出字段
let fields: any = {};
props.tableHead.forEach(item => {
    fields[item.label] = item.prop;
});

// tableRowClassName({ row, rowIndex }) {
//       if (rowIndex % 2 == 0) {
//         return "";
//       } else {
//         return "statistics-warning-row";
//       }
//     }
interface changeRowParameter {
    row: any;
    rowIndex: number;
}
const tableRowClassName = ({ row, rowIndex }: changeRowParameter) => {
    if (rowIndex % 2 == 0) {
        return '';
    } else {
        return 'statistics-warning-row';
    }
};
/*
 *   活动告警
 */
// 活动告警数
const alarmSum = ref();
setTimeout(() => {
    reqGetAlarmSum().then(res => {
        alarmSum.value = res;
    });
}, 5000);

// 获取实例

const FileName = ref('');
// 导出为 excel
function exportExcel(fileName: string = 'data') {
    FileName.value = fileName;
    try {
        // @ts-ignore
        const tableEle = this.$el as HTMLElement;
        let $table = tableEle.querySelector('.el-table__fixed');
        if (!$table) {
            $table = tableEle;
        }
        const wb = XLSX.utils.table_to_book($table, { raw: true });
        const wbout = XLSX.write(wb, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array',
        });
        FileSaver.saveAs(
            new Blob([wbout], {
                type: 'application/octet-stream',
            }),
            `${FileName.value}.xlsx`,
        );
    } catch (e) {
        if (typeof console !== 'undefined') console.error(e);
    }
}

// 将方法暴露出去
defineExpose({
    exportExcel,
});
</script>

<style lang="scss" scoped>
:deep(.is-group tr) {
    background-color: #fff !important;
}
article {
    height: 100%;
    overflow: hidden;

    // &[theme='one'] {
    //     :deep(.el-table) {
    //         color: red;
    //     }
    // }
    :deep(.el-table) {
        color: #1d2129;
        background-color: transparent;

        --el-table-border-color: #8291a9;
        --el-table-border: 0.5px solid var(var(--el-table-border-color));
        --el-table-current-row-bg-color: #162335;
        color: #8291a9;
        // 清除table表格的下边线
        --el-table-border-color: none;

        tr {
            // background-color: #062139;
            background-color: #0c1c30;
        }

        .current-row,
        .el-table__expand-icon {
            color: #fff;
        }

        .el-table__expand-icon {
            font-weight: 900;
        }

        .el-table__header {
            th {
                padding-top: vh(5);
                // 表头字体颜色
                color: rgba(255, 255, 255, 0.6);
                background-color: #12223a !important;
                // border: vh(1) solid #0e1e33;
            }
        }
        // 给td高度
        td {
            padding-top: vh(3);
        }

        // 单行显示的颜色
        .el-table__row.statistics-warning-row {
            // background: #092b49;
            background: #0e1e33;
        }

        .el-table__body tr:hover > td.el-table__cell,
        .el-table__expanded-cell {
            // background-color: #0f1011 !important;
            background-color: rgba($color: #000000, $alpha: 0.4) !important;
            color: rgba($color: #fff, $alpha: 0.8);
        }

        .el-table__empty-block {
            // background-color: #fff;
            background-color: #08172a;
            --el-text-color-secondary: rgba(255, 255, 255, 0.6);
        }
    }
}
</style>

getValue.ts文件代码如下

export default function getValue(target: any, propNames: string) {
    let propNameList = propNames ? propNames.split('.') : [];
    let res: any = target;
    if (propNameList.length > 0) {
        res = getValue(target[propNameList.shift() as string], propNameList.join('.'))
    }
    return res;
}

念 2022.10.24小饭桶

                                               墨羽

猜你喜欢

转载自blog.csdn.net/weixin_68531033/article/details/127491869