封装原生html的table处理方法【参数类似eltable】

直接跑html即可

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>封装原生talbe</title>
</head>
<body>
  <div id="table_content"></div>
</body>

<script>
  // ---------------------------------------------------------封装开始------------------
  // 把vNode对象转为html字符串
  function vnodeToString(vnode) {
    // 如果是文本节点,直接返回文本内容
    if (['string', 'boolean', 'undefined', 'null', 'number'].includes(typeof vnode) || !vnode) {
      return vnode;
    }
    // 转换节点的属性为字符串形式
    const attrs = Object.keys(vnode.attrs || {})
      .map((key) => `${key}="${vnode.attrs[key]}"`)
      .join(' ');
    // 转换子节点为字符串形式
    const children = (vnode.children || [])
      .map(vnodeToString)
      .join('');
    // 返回包含标签名、属性和子节点的字符串形式
    return `<${vnode.tag} ${attrs}>${children}</${vnode.tag}>`;
  }



  class DataToExcelHtml {
    // 原始数据
    originalData = []
    // 表格列配置数据
    columnsData = []
    // 渲染数据vNode
    renderData = []
    // 表头vNode数据
    headerVNode = []
    // 表体vNode数据
    bodyVNode = []

    // 列宽
    colWidth = 120


    constructor(config) {
      this.dom = config.dom
      this.colWidth = config.colWidth || 120
      this.originalData = config.data
      this.columnsData = config.columnsData
      this._setColIndex()
      this.headerVNode = this._setHeaderVNode()
      this.bodyVNode = this._setBodyVNode()
      this.setInnerHtml()
    }


    // 取最后一层
    flattenObjectArrayLast(arr, key = "children") {
      let flattened = [];
      arr.forEach(v => {
        if (v.children && v.children.length > 0) {
          flattened = flattened.concat(this.flattenObjectArrayLast(v[key]))
        } else {
          flattened.push(v);
        }
      })
      return flattened;
    }

    // 表头   设置每个字段所在的列 行下标值
    _setColIndex(data = this.columnsData, index = 0, row_index = 0) {
      data.forEach(v => {
        v.__colspan = this.flattenObjectArrayLast(v.children || []).length || 1
        v.__rowspan = v.rowspan || 1
        v.__col_index = v.__colspan > 1 ? null : index
        v.__row_index = row_index
        index++
        if (v.children?.length) {
          index = this._setColIndex(v.children, index, row_index + 1)
        }
      })
      return index
    }

    // 设置样式
    _setStyle(col) {
      // 表样式通用
      const commonTrStyle = "height: 30px;"
      const commonBorder = 'border-width:1px;border-style:solid;border-color:#000000;'
      const commonAttrsLabel = {
        style: `text-align:${col.align || 'center'};font-size: 12px;` + commonBorder + commonTrStyle + col.styleStr,
      }
      return commonAttrsLabel
    }

    // 设置表头
    _setHeaderVNode(data = this.columnsData) {
      const that = this
      // 递归获取表头合并行深度
      let deep = (function getDeep(list) {
        let deep = 1
        list.forEach(col => {
          let curDeep = 1
          if (col.children && col.children.length) {
            curDeep += getDeep(col.children)
          }
          deep = curDeep > deep ? curDeep : deep
        })
        return deep
      })(data)



      // 递归获取表头VNode
      this.headerVNode = (function recData(list, curDeep = 1, tr = []) {
        list.forEach(col => {
          tr[col.__row_index] = tr[col.__row_index] || { tag: 'tr', children: [] }
          const obj = {
            tag: 'td',
            children: [col.label],
            attrs: {
              style: that._setStyle(col).style,
              rowspan: col.__rowspan || 1,
              colspan: col.__colspan || 1,
              width: col.width || that.colWidth,
            }
          }
          if (col.children) {
            recData(col.children, curDeep++, tr)
          } else if (!col.children?.length) {
          }
          tr[col.__row_index].children.push(obj)
        })
        return tr
      })(data)
      return this.headerVNode
    }

    _setBodyVNode(data = this.originalData, columnsData = this.columnsData) {
      const flatColumns = this.flattenObjectArrayLast(columnsData).filter(v => v.__col_index !== null)
      function getChild(row, col, index) {
        if (col.type === 'index') {
          return index + 1
        }
        return row[col.prop] || ''
      }
      this.bodyVNode = data.map((row, index) => {
        const tr = { tag: 'tr', children: [] }
        // 列下标
        flatColumns.forEach((col, idx) => {
          tr.children.push({
            tag: 'td',
            children: [getChild(row, col, index)],
            attrs: {
              style: this._setStyle(col).style,
            }
          })
        })
        return tr
      })
      return this.bodyVNode
    }

    // 设为innerHtml
    setInnerHtml(vNode = this.headerVNode) {
      const i = vnodeToString({
        tag: 'table',
        attrs: {
          style: "border-collapse: collapse;border:1px",
          border: 1,
          id: 'excel-line-data'
        },
        children: [{
          tag: 'tbody',
          attrs: {
            style: ""
          },
          children: [].concat(vNode, this.bodyVNode)
        }]
      })
      this.dom.innerHTML = i
    }
  }
  // ---------------------------------------------------------封装结束------------------

  // ---------------------------------------------------------调用
  new DataToExcelHtml({
    dom: document.querySelector('#table_content'),
    data: [
      { tlj: '测试1', time: '2023年', status: '001' },
      { tlj: '测试2', time: '2023年', status: '001' },
      { tlj: '测试3', time: '2023年', status: '001' },
      { tlj: '测试4', time: '2023年', status: '001' },
    ],
    columnsData: [
      {
        label: '标题',
        styleStr: 'color: red; font-size: 30px; font-weight: 700',
        children: [
          {
            label: 'xxx时间',
            align: 'left',
            children: [
              {
                label: "序号",
                type: 'index',
                rowspan: 2,
              },
              {
                label: "姓名",
                prop: 'tlj',
                width: 300,
                rowspan: 2,
              },
              {
                label: "---",
                children: [
                  {
                    label: "时间",
                    width: 300,
                    prop: "time"
                  },
                  {
                    label: "状态",
                    prop: "status",
                  },
                ]
              },
            ]
          }
        ]
      }
    ]
  })


</script>

<style>
  td {
    box-sizing: border-box;
    white-space: nowrap;
    min-width: 100px;
  }

  table {
    table-layout: fixed;
  }

  td {
    padding: 0 10px;
  }

  #table_content {
    overflow-x: auto;
  }
</style>

</html>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
封装el-table是指将element-ui中的el-table组件进行二次封装,以便于在项目中更方便地使用。根据引用\[1\]所提到的功能,封装el-table可以包含以下功能: 1. 多选:可以通过配置实现el-table的多选功能,使用户可以选择多行数据。 2. 排序:可以通过配置实现el-table的排序功能,使用户可以根据某一列的值进行升序或降序排列。 3. 常见状态{code,msg}:可以通过配置实现el-table中常见的状态展示,比如显示错误码和错误信息等。 4. 自定义column内容:可以通过配置实现el-table中列的自定义内容展示,比如可以在某一列中显示图片或其他自定义的内容。 5. switch开关:可以通过配置实现el-table中的开关功能,使用户可以在表格中进行开关操作。 6. 图片:可以通过配置实现el-table中显示图片的功能,比如在某一列中展示图片。 7. 点击任意不含前面类型的文字,可编辑:可以通过配置实现el-table中的编辑功能,使用户可以点击某一列的文字进行编辑操作。 8. 行操作:可以通过配置实现el-table中的行操作功能,比如在每一行中添加操作按钮,实现对该行数据的操作。 综上所述,封装el-table可以满足常见的table列表需求,并且可以根据具体项目的需求进行功能的扩展和定制。 #### 引用[.reference_title] - *1* [el-table封装elementtable封装eltable封装详解(含分页)](https://blog.csdn.net/qq_37346639/article/details/115556605)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值