vue3基于elementplus 简单实现表格二次封装过程

 更新时间:2024年05月14日 11:17:59   作者:维他命Coco  
公司渲染表格数据时需要将空数据显示‘-’,并且对于每一列数据的显示也有一定的要求,基于这个需求对element-plus简单进行了二次封装,这篇文章主要介绍了vue3基于elementplus 简单实现表格二次封装过程,需要的朋友可以参考下

公司渲染表格数据时需要将空数据显示‘-’,并且对于每一列数据的显示也有一定的要求,基于这个需求对element-plus简单进行了二次封装。
具体包括以下几点(持续更新中):
1.空数据显示‘-’
2.固定表格高度
3.支持多选表格
4. 自定义列宽

<template>
  <div>
    <el-table
      :data="dataSource"
      v-loading="loading"
      :height="vdaH"
      :max-height="vdaH"
      :fit="fit"
      :border="border"
      :header-cell-class-name="headerCellClassName"
      highlight-current-row
      :tooltip-options="{
        effect: 'dark',
        placement: 'bottom',
        showArrow: true,
      }"
      show-overflow-tooltip
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="isMoreSelect"
        type="selection"
        width="55"
        :selectable="handleSelectable"
      />
      <el-table-column type="index" label="序号" width="55" />
      <template v-for="(column, index) in columns" :key="index">
        <el-table-column
          show-overflow-tooltip
          v-if="column.scopeVal"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.width || column.label.length * 20 + 20"
        >
          <template #default="scope">
            <slot
              :column="column"
              :record="scope.row"
              :text="scope.row[column.prop]"
              :index="dataSource.indexOf(scope.row)"
              :name="column.prop"
            >
            </slot>
          </template>
        </el-table-column>
        <!-- :min-width="column.width || column.label.length * 20 + 20" -->
        <el-table-column
          v-else
          :prop="column.prop"
          :label="column.label"
          :min-width="
            column.width ||
            getColumnWidth(column.label, column.prop, dataSource)
          "
        >
          <template #default="{ row }">
            {{ checkEmpty(row[column.prop]) }}
          </template>
        </el-table-column>
      </template>
      <!-- 操作 -->
      <el-table-column
        v-if="!hideOperation"
        fixed="right"
        label="操作"
        align="center"
        :width="operationWidth"
      >
        <template #default="scope">
          <slot v-bind="scope"></slot>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-show="totalNum > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page.sync="page"
        :page-sizes="[10, 20, 50, 100]"
        v-model:page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        background
        small
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { checkEmpty, getColumnWidth } from "@/utils/util";
const props = defineProps({
  dataSource: {
    type: Array<any>,
    default: () => [],
  },
  columns: {
    type: Array<any>,
    default: () => [],
  },
  vdaH: {
    type: Number,
    default: 300,
  },
  hideOperation: {
    type: Boolean,
    default: false,
  },
  operationWidth: {
    type: String,
    default: "100",
  },
  loading: {
    type: Boolean,
    default: false,
  },
  //是否多选显示
  isMoreSelect: {
    type: Boolean,
    default: false,
  },
  fit: {
    type: Boolean,
    default: true,
  },
  border: {
    type: Boolean,
    default: false,
  },
  headerCellClassName: {
    type: String,
    default: "custmorTableHeader",
  },
  // 当前页
  currentPage: {
    type: Number,
    default: 0,
  },
  // 展示页数
  pageSize: {
    type: Number,
    default: 0,
  },
  //总页数
  totalNum: {
    type: Number,
    default: 0,
  },
  //多选
  handleSelection: {
    type: Function,
    default: () => {},
  },
});
// // 测试列宽
// /**
//  * el-table扩展工具  -- 列宽度自适应
//  * @param {*} prop 字段名称(string)
//  * @param {*} records table数据列表集(array)
//  * @returns 列宽(int)
//  */
// function getColumnWidth(prop: string, records: any) {
//   const minWidth = 80; // 最小宽度
//   const padding = 12; // 列内边距
//   const contentWidths = records.map((item: any) => {
//     console.log("item", item);
//     console.log("PROP", prop);
//     const value = item[prop] ? String(item[prop]) : "";
//     const textWidth = getTextWidth(value);
//     return textWidth + padding;
//   });
//   console.log("contentWidths", contentWidths);
//   let maxWidth = Math.max(...contentWidths);
//   if (maxWidth > 240) {
//     maxWidth = 240;
//   }
//   return Math.max(minWidth, maxWidth);
// }
// /**
//  * el-table扩展工具  -- 列宽度自适应 - 获取列宽内文本宽度
//  * @param {*} text 文本内容
//  * @returns 文本宽度(int)
//  */
// function getTextWidth(text: string) {
//   const span = document.createElement("span");
//   span.style.visibility = "hidden";
//   span.style.position = "absolute";
//   span.style.top = "-9999px";
//   span.style.whiteSpace = "nowrap";
//   span.innerText = text;
//   document.body.appendChild(span);
//   const width = span.offsetWidth + 5;
//   document.body.removeChild(span);
//   return width;
// }
// ...其他方法
const emit = defineEmits([
  "pagination",
  "update:currentPage",
  "update:pageSize",
  "selection-change",
]);
const page = useVModel(props, "currentPage", emit);
const size = useVModel(props, "pageSize", emit);
function handleSizeChange(val: number) {
  emit("pagination", { currentPage: page, pageSize: val });
}
function handleCurrentChange(val: number) {
  // console.log("val", val);
  page.value = val;
  emit("pagination", { currentPage: val, pageSize: props.pageSize });
}
const handleSelectionChange = (val: any) => {
  emit("selection-change", val);
};
const handleSelectable = (row: any) => {
  // console.log("row", row);
  return row.selectable;
};
</script>
<style lang="scss" scoped>
.pagination {
  display: flex;
  justify-content: end;
  padding: 12px;
  margin-top: 5px;
  &.hidden {
    display: none;
  }
}
</style>

对于表格列宽实现了根据数据长度进行每一列的展示:

/**
 * el-table扩展工具  -- 列宽度自适应
 * @param {*} prop 字段名称(string)
 * @param {*} records table数据列表集(array)
 * @returns 列宽(int)
 */
export function getColumnWidth(label: string, prop: string, tableData: any) {
  //label表头名称
  //prop对应的内容
  //tableData表格数据
  const minWidth = 90; // 最小宽度
  const padding = 10; // 列内边距
  const arr = tableData.map((item: any) => item[prop]);
  arr.push(label); //拼接内容和表头数据
  const contentWidths = arr.map((item: any) => {
    // console.log("item", item);
    // console.log("PROP", prop);
    const value = item ? String(item) : "";
    const textWidth = getTextWidth(value);
    return textWidth + padding;
  });
  // console.log("contentWidths", contentWidths);
  let maxWidth = Math.max(...contentWidths);
  if (maxWidth > 240) {
    maxWidth = 240;
  }
  return Math.max(minWidth, maxWidth);
}
/**
 * el-table扩展工具  -- 列宽度自适应 - 获取列宽内文本宽度
 * @param {*} text 文本内容
 * @returns 文本宽度(int)
 */
function getTextWidth(text: string) {
  const span = document.createElement("span");
  span.style.visibility = "hidden";
  span.style.position = "absolute";
  span.style.top = "-9999px";
  span.style.whiteSpace = "nowrap";
  span.innerText = text;
  document.body.appendChild(span);
  const width = span.offsetWidth + 5;
  document.body.removeChild(span);
  return width;
}

到此这篇关于vue3基于elementplus 简单实现表格二次封装过程的文章就介绍到这了,更多相关vue表格二次封装内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • element-ui表格如何自适应高度效果示例

    element-ui表格如何自适应高度效果示例

    这篇文章主要给大家介绍了关于element-ui表格如何自适应高度的相关资料,Element UI的Table组件默认情况下是没有自适应高度的,文中给大家介绍了解决的办法,需要的朋友可以参考下
    2023-08-08
  • 学习 Vue.js 遇到的那些坑

    学习 Vue.js 遇到的那些坑

    这篇文章主要介绍了学习 Vue.js 遇到的那些坑,帮助大家更好的理解和使用vue框架,感兴趣的朋友可以了解下
    2021-02-02
  • vue滚动tab跟随切换效果

    vue滚动tab跟随切换效果

    这篇文章主要为大家详细介绍了vue滚动tab跟随切换效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-07-07
  • vue路由跳转了但界面不显示的问题及解决

    vue路由跳转了但界面不显示的问题及解决

    这篇文章主要介绍了vue路由跳转了但界面不显示的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-04-04
  • Vue实现选项卡tab切换制作

    Vue实现选项卡tab切换制作

    这篇文章主要为大家详细介绍了Vue实现选项卡tab切换制作,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • vue实现列表无缝动态滚动

    vue实现列表无缝动态滚动

    要想实现列表的动态无缝滚动,本文为大家推荐两款组件,vue-seamless-scroll和vue3-seamless-scroll,组件的用法也非常简单,下面就跟随小编一起来学习一下吧
    2024-11-11
  • Vue源码探究之状态初始化

    Vue源码探究之状态初始化

    这篇文章主要介绍了Vue源码探究之状态初始化,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • vue项目使用node连接数据库的方法(前后端分离)

    vue项目使用node连接数据库的方法(前后端分离)

    这篇文章主要介绍了vue项目使用node连接数据库(前后端分离),本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-12-12
  • vue-cli项目根据线上环境分别打出测试包和生产包

    vue-cli项目根据线上环境分别打出测试包和生产包

    这篇文章主要介绍了vue-cli项目根据线上环境打出测试包和生产包的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • 浅谈Vue3 Composition API如何替换Vue Mixins

    浅谈Vue3 Composition API如何替换Vue Mixins

    这篇文章主要介绍了浅谈Vue3 Composition API如何替换Vue Mixins,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04

最新评论