✅正確打開列表花樣玩法
項目要求
1. 表格高亮目標行
2. 表格目標行不在可視范圍,自動定位到表格中間。
3. 前端搜索定位,搜索列表匹配數據,高亮然后定位
4. 多列排序,高亮當前排序列
技術棧
vue + antd-vue
思路
1. 高亮列表,自定義列表行的className,然后設置樣式。使用table的rowClassName。
2. 自動定位列表數據,列表數據渲染完后獲取table距離頁面頂部的距離、高亮行距離頁面頂部距離、table的可視高度,用高亮行top - table的top - table的高度 / 2(除以2是為了將高亮行顯示在table的中間,不減顯示在第一行)。
3. 輸入關鍵字搜索,因為要高亮行,所以得重新渲染列表。首先遍歷數據,匹配關鍵字數據設置標志位,高亮思路同上。
4. 高亮當前排序列:其實也就是自定義渲染數據樣式,tableChange的時候獲取到當前被排序的column的dataIndex,存入全局。然后在渲染數據時判斷是否為排序行數據,給其樣式。
代碼實現
1. 渲染列表動態設置rowClassName
ra-table.mgt-16( rowKey="cityCode" :data-source="data" :scroll="{y: scrollAreaHeight}" :rowClassName="setRowClass" @change="tableChange") // 設置當前城市高亮類 record為當前行數據 setRowClass(record) { if (record.cityCode === this.cityCode) return 'rowhighlight' } // .css .rowhighlight { background: #F0F7FF; }
2. 自動定位列表,scrollBy(x, y)表示相對現在的位置橫向移動x,縱向移動y。也可以像我設置滾動的行為,我們希望它能平滑滾動,有一個過渡的效果,還可以設置滾動的時長。
// 定位高亮列 setTableScroll() { this.$nextTick(() => { const tableEle = document.querySelector('.ant-table-body') const highlightRowEle = document.querySelector('.rowhighlight') const tableEleTop = tableEle && tableEle.getBoundingClientRect().top const tableEleClientHeight = tableEle && tableEle.getBoundingClientRect().height const highlightRowEleTop = highlightRowEle && highlightRowEle.getBoundingClientRect().top const scroll = highlightRowEleTop - tableEleTop - tableEleClientHeight / 2 tableEle.scrollBy({ top: scroll, behavior: 'smooth' }) }) },
3. 搜索列表數據匹配高亮,實現方式同上,這里不再贅述。
4. 高亮當前排序列,樣式根據業務自行替換
a-table.mgt-16( rowKey="cityCode" :data-source="data" :scroll="{y: scrollAreaHeight}" :rowClassName="setRowClass" @change="tableChange") a-table-column( v-for="column in columns" :title="column.title" align="center" :sorter="column.sorter" :defaultSortOrder="column.defaultSortOrder" :key="column.dataIndex") template(slot-scope="text, record") div( :style="getItemClass(record, column)" :title="record[column.dataIndex]") {{record[column.dataIndex]}} // fcvToColor 是根據當前值獲取的顏色,可忽略 getItemClass(record, column) { // 判斷當前行是否為排序行 if (!column.sorter || column.dataIndex !== this.currentSorterKey) return const color = fcvToColor(record[column.dataIndex], column.key, 0) return { width: '40px', height: '22px', color: '#FFFFFF', background: color, borderRadius: '11px', margin: '0 auto', } },