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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3中使用Element Plus的表格,你需要先安装Element Plus并在你的Vue项目中引入它。以下是一些基本的步骤: 1. 首先,确保你的Vue项目已经创建并且已经安装了Vue 3。 2. 安装Element Plus。你可以使用npm或者yarn来安装Element Plus。在终端中运行以下命令: ``` npm install element-plus ``` 或者 ``` yarn add element-plus ``` 3. 在你的Vue项目的入口文件(通常是main.js)中引入Element Plus的样式和组件。在main.js中添加以下代码: ```javascript import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' const app = createApp(App) app.use(ElementPlus) app.mount('#app') ``` 这样就完成了Element Plus的安装和引入。 4. 在你的Vue组件中使用Element Plus的表格组件。你可以在你的组件模板中使用`el-table`标签来创建表格,然后在`el-table-column`标签中定义表格的列。以下是一个简单的例子: ```vue <template> <el-table :data="tableData"> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> <el-table-column prop="gender" label="性别"></el-table-column> </el-table> </template> <script> export default { data() { return { tableData: \[ { name: '张三', age: 20, gender: '男' }, { name: '李四', age: 25, gender: '女' }, { name: '王五', age: 30, gender: '男' } \] } } } </script> ``` 在这个例子中,我们使用了`el-table`标签创建了一个表格,并使用`el-table-column`标签定义了表格的列。`tableData`是一个包含数据的数组,用于渲染表格的内容。 这样,你就可以在Vue 3中使用Element Plus的表格了。你可以根据Element Plus的文档进一步了解表格组件的更多用法和配置选项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值