Build a wheel and implement a table component (UniApp) for a complex scene

Build a wheel and implement a table component (UniApp) for a complex scene

Get into the habit of writing together! This is the first day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

I am a mature programmer, and I need to know how to make my own wheels. The purpose of this article is to review + record.
Usage scenarios: uniApp , mobile terminal (compatible with applet, App, H5)

The subject

Organize specific functions according to your needs:

need to organize

  1. form name
    1. Configurable background
    2. Font style can be modified (size, color)
    3. Menu button (requires external exposure events)
  2. header
    1. Supports multi-level headers
    2. Fixed header
    3. Header row supports custom names
  3. sheet
    1. Support setting cell width
    2. fixed first column
    3. Support tree data
    4. Content supports pictures and links
  4. other
    1. Internal implementation sorting
    2. Implement paging internally
    3. Internally calculated total line

Some thoughts on the whole assembly

  1. The function is more complex, and it is not elegant and messy to squeeze into one file -> divided into several modules in a large direction (fine granularity)
  2. There are many requirements, and it is intuitive that there are many parameters to be passed -> According to the module definition, the parameters are also classified
  3. There are many parameters, how to manage it more elegantly and reduce the difficulty of getting started? -> Configuration file config.jsand set default values ​​in it, which play the role of field description and default state management
  4. Which will involve the use of some icons -> selected iconfonticon library

Difficulties in Technical Implementation

Due to the limitations of the use environment: uniAppthe implemented form-related components are relatively simple, and the restrictions on non-H5 environments are relatively large (for example, it cannot be set rowspan, colspan), and it is also troublesome to use, which cannot meet the needs of the project, and finally decided to build a wheel.

header part

主要难点在于 多级表头的处理,怎么样做到根据数据来驱动显示。刚开始是打算按 html table 的方式实现,开发过程中遇到的问题比较多,首先数据处理比较麻烦,要计算有多少行、每行单元格的colspanrowspan。而且没有td, tr等组件,需要自己额外实现。

columns的数据是树形的,如下

columns = [
    { "title": "区域", "dataIndex": "区域" },
	{
		"title": "广州一区",
		"children": [
			{ "title": "销售", "dataIndex": "广州一区销售"},
			{ "title": "计划销售", "dataIndex": "广州一区计划销售" },
			{ "title": "达成", "dataIndex": "广州一区达成"}
		]
	},
    // ...
]

复制代码

似乎用 flex 布局就能实现了
每个格子设置垂直居中,如果存在children则遍历递归渲染,由于需要递归调用渲染,把递归的部分在分出来一个组件:titleColumn 。先贴个代码(代码已发布到社区,有兴趣可以去看看 传送门):

table-header.vue
table-header

titleColumn.vue title-column

这里有个坑
在正常的vue中递归组件是不需要引入的,在 uniApp则需要。

// titleColumn.vue
import titleColumn from "./title-column.vue"
复制代码

样式方面不展开了,不好写。直接看看效果(自我感觉很好,哈哈哈):
header effect

表格内容

这里先要处理下columns的数据(要考虑到多级表头情况),根据上面的columns,得到实际要渲染的列:

  1. 新建一个变量dataIndexs,用于保存需要实际渲染的列数据
  2. 递归处理columns拿到最终的 叶子节点 并保存起来。

关键代码:

// 根据Column 获取body中实际渲染的列
fmtColumns(list) {
    // 保存叶子节点
    this.dataIndexs = []
    if (!list || !list.length) return
    // 获取实际行
    this.columnsDeal(list)
},

// 
columnsDeal(list, level = 0) {
    list.forEach(item => {
        let { children, ...res } = item
        if (children && children.length) {
            this.columnsDeal(children, level + 1)
        } else {
            this.dataIndexs.push({ ...res })
        }
    })
},
复制代码

接下来就是处理列表数据中的树形结构了。
先看看数据结构 tableData:

tableData = [
    {
		"key": 1,
		"区域": "广州",
		"销售": 100,
		"计划销售": 200,
		"达成": "50.0%",
		"达成排名": 1,
		"GroupIndex": 1,
		"GroupLayer": 1,
		"GroupKey": "广州",
		"children": [{
				"key": 11,
				"区域": "广州一区",
				"小区": "广州一区",
				"销售": 60,
				"计划销售": 120,
				"达成": "50.0%",
				"达成排名": 1,
				children: [{
					"key": 111,
					"区域": "广州一区1",
					"小区": "广州一区1",
					"销售": 60,
					"计划销售": 120,
					"达成": "50.0%",
					"达成排名": 1,
				}]
			},
			{ "key": 12, "区域": "广州二区", "小区": "广州二区", "销售": 40, "计划销售": 80, "达成": "50.0%", "达成排名": 1 },
		],
	},
]
复制代码

树形的结构,key是唯一值。
有想过使用递归组件的方式实现,但是考虑到会涉及到展开、收起的操作。也是比较麻烦。
最终的方案是把数据扁平化处理,为每条数据添加 层级、是否子数据、父级ID 等属性。并通过一个数组变量来记录展开的行,并以此控制子数据的显示与否。处理后的数据存放在 dataList
扁平化处理函数:

// 递归处理数据,tree => Array
listFmt(list, level, parentIds = []) {
    return list.reduce((ls, item) => {
        let { children, ...res } = item
        // 错误提示
        if (res[this.idKey] === undefined || !res[this.idKey] === null) {
            // console.error(`tableData 数据中存在 [idKey] 属性不存在数据,请检查`)
        }
        let nowItem = {
            ...res,
            level,
            hasChildren: children && children.length,
            parentIds,
            children,
            [this.idKey]: res[this.idKey] && res[this.idKey].toString()
        }
        ls.push(nowItem)
        if (children && children.length) {
            this.isTree = true
            ls = ls.concat(this.listFmt(children, level + 1, [...parentIds, nowItem[this.idKey]]))
        }
        return ls
    }, [])
},
复制代码

最终得到的数据如下:
dataList table data

数据处理完可以渲染了,
需要嵌套两层遍历:
第一层 遍历 dataList 得到行
第二层 遍历 dataIndexs 得到列
最终完成渲染:
1649230027(1)

固定首列,固定表头

使用css属性:position: sticky实现。粘性定位元素(stickily positioned element)。大家都是成熟的前端程序猿啦~~,就不具体介绍了。说说一些需要注意的细节:
兼容性
sticky compatibility
uniapp中小程序模式、App模式是支持的!!!

限制

  1. 设置了position:sticky之后必现指定top left right bottom其中任一,才会生效。不设置的话表现和相对定位相同。topbottom 或者 leftright 同时设置的情况下,topleft的优先级高。

  2. 设定为 position:sticky 元素的任意父节点的 overflow 属性必须是visible,否则 不会生效 (都不能滚动还能咋办)。

其他

造个轮子不难,造个好用的轮子不易。

Some things related to layout and CSS are not easy to express in the article. I won't go into details. If you are interested, you can pull the code to see. portal

During the development process, we also encountered many problems, all of which were tinkered along the way. Failure to conceive well in the early stage will lead to bumps in the subsequent development (the modules and parameters were not divided well at the beginning, and the logic of the whole thing was rather chaotic. I stopped to rethink and adjust, there is a kind of joy that suddenly opens up)

Move the bricks~

Guess you like

Origin juejin.im/post/7083401121486045198