【fix 66426】JTable拖拽效果案例及md文档

This commit is contained in:
danshihao
2023-03-17 16:39:10 +08:00
parent 84b7f94367
commit 395d8599f4
4 changed files with 438 additions and 96 deletions
+1
View File
@@ -36,6 +36,7 @@
"vue": "^2.6.10", "vue": "^2.6.10",
"vue-area-linkage": "^5.1.0", "vue-area-linkage": "^5.1.0",
"vue-cropper": "^0.5.4", "vue-cropper": "^0.5.4",
"vue-draggable-resizable": "^2.3.0",
"vue-i18n": "^8.7.0", "vue-i18n": "^8.7.0",
"vue-loader": "^15.7.0", "vue-loader": "^15.7.0",
"vue-ls": "^3.2.0", "vue-ls": "^3.2.0",
+170 -43
View File
@@ -1,8 +1,12 @@
<template> <template>
<a-table <a-table
ref='table' class="j-table"
ref="table"
:bordered="bordered"
:table-key="tableKey" :table-key="tableKey"
:columns="resultColumns" :columns="resultColumns"
:components="components"
:scroll="scroll || selfScroll"
v-bind="$attrs" v-bind="$attrs"
v-on="$listeners"> v-on="$listeners">
@@ -12,7 +16,6 @@
<div slot="settingDropdown"> <div slot="settingDropdown">
<a-card> <a-card>
<!-- scroll.x 要大于表格所有固定列宽的合每个列都要有width否则定位后宽度会出现变形否则会出现问题 -->
<a-table <a-table
rowKey="key" rowKey="key"
:style="settingStyle" :style="settingStyle"
@@ -43,8 +46,10 @@
<script> <script>
import Vue from 'vue' import Vue from 'vue'
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
import VueDraggableResizable from 'vue-draggable-resizable'
Vue.component('vue-draggable-resizable', VueDraggableResizable)
// 操作列的key或dataIndex
const actionKey = 'action' const actionKey = 'action'
// 保存localStorage中的后缀 // 保存localStorage中的后缀
const saveSuffix = ':JTable' const saveSuffix = ':JTable'
@@ -52,24 +57,10 @@ const saveSuffix = ':JTable'
const getKey = col => col.key || col.dataIndex const getKey = col => col.key || col.dataIndex
// 所有JTable的缓存key // 所有JTable的缓存key
const J_TABLE_KEYS = 'J_TABLE_KEYS' const J_TABLE_KEYS = 'J_TABLE_KEYS'
/**
* 以下 表格为实际要展示的表、配置表为设置冻结和隐藏的表
* 执行流程梳理
* 1.mounted挂载时去拿配置
* 1.1.从localStorage取历史配置:取到直接进入2 没取到就进1.2
* 1.2.从父组件获取columns初始化配置 并存储到localStorage
*
* 2.拿到配置后
* 2.1.watch进行监听配置,然后生成 配置表格的数据,再调用setResultColumns来更新表格
* 2.2.将columns根据配置转换成resultColumns进行渲染表格
*
* 3.修改配置触发changeSetting来对配置进行更新,更新后watch会监听到跳转2如此循环
*/
export default { export default {
name: 'JTable', name: 'JTable',
props: { props: {
// 用于持久化存储列配置,保证唯一
tableKey: { tableKey: {
type: String, type: String,
required: true required: true
@@ -89,6 +80,21 @@ export default {
type: Object, type: Object,
required: false, required: false,
default: () => ({ y: 300 }) default: () => ({ y: 300 })
},
// 如果需要拖拽后增加总列宽而不是占用其他列宽度:需要父组件 :scroll.sync="scroll"
scroll: {
type: Object,
required: false
},
// 列最小宽度
columnMinWidth: {
type: Number,
required: false,
default: 100
},
bordered: {
type: Boolean,
required: false
} }
}, },
data () { data () {
@@ -101,7 +107,13 @@ export default {
], ],
settingDataSource: [], settingDataSource: [],
settingColumnsObj: { hide: [], freeze: [] }, // 本地存储的配置对象 settingColumnsObj: { hide: [], freeze: [] }, // 本地存储的配置对象
resultColumns: [] resultColumns: [],
components: {
header: {
cell: this.initDrag(this.columns)
}
},
selfScroll: {}
} }
}, },
computed: { computed: {
@@ -113,7 +125,7 @@ export default {
} }
} }
return slots return slots
}, }
}, },
watch: { watch: {
// 配置列改变,将配置转换成配置表格数据 // 配置列改变,将配置转换成配置表格数据
@@ -147,29 +159,116 @@ export default {
} }
}, },
methods: { methods: {
// 初始化表格拖拽
initDrag (tbCols) {
// 没有边框就不能拖拽
if (!this.bordered) {
return
}
// 如果没有任何列开启拖拽就不需要拖拽
if (!tbCols.some(col => col.resizable)) {
return
}
// 第一步:列宽映射
const draggingMap = {}
tbCols.forEach((col) => {
draggingMap[col.dataIndex || col.key] = col.width
})
const draggingState = Vue.observable(draggingMap)
// 第二步:表头渲染
return (h, props, children) => {
// 表头DOM
let thDom = null
// 获取列的key值和特性
const { key, ...restProps } = props
// if (renderField.includes(key)) {
// return
// }
// renderField.push(key)
// 获取当前列
// const col = tbCols.find((col) => {
// const k = col.dataIndex || col.key
// return k === key
// })
let col
if (key === 'selection-column') {
col = {}
} else {
col = this.columns.find(col => getKey(col) === key)
}
// 没有开启拖拽 或 没有宽度 或 有定位,都不能拖拽(防止布局异常,至少有一列不设width并且不能有fixed)
if (!col.resizable || !col.width || !!col.fixed) {
return <th {...restProps}>{children}</th>
}
// 开始拖拽监听
const onDrag = (x) => {
const beforeWidth = col.width
const scroll = cloneDeep(this.scroll) || {}
draggingState[key] = 0
col.width = Math.max(x, col.minWidth || this.columnMinWidth)
// 如果有scroll.x就计算差值,否则获取所有列的和
if (scroll.x) {
scroll.x = scroll.x + (col.width - beforeWidth)
} else {
scroll.x = 0
this.columns.forEach(col => (scroll.x += (col.width || col.minWidth || this.columnMinWidth)))
}
// 将计算好的宽度更新
if (this.scroll) {
this.$emit('update:scroll', scroll)
} else {
this.selfScroll = scroll
}
}
// 停止拖拽监听
const onDragstop = () => {
draggingState[key] = thDom.getBoundingClientRect().width
}
return (
<th
{...restProps}
v-ant-ref={(r) => (thDom = r)}
width={col.width}
class="resize-table-th"
>
{children}
<vue-draggable-resizable
key={col.dataIndex || col.key}
class="table-draggable-handle"
minw={10}
w={10}
x={col.width || draggingState[key]}
z={1}
axis="x"
draggable={true}
resizable={false}
onDragging={onDrag}
onDragstop={onDragstop}
></vue-draggable-resizable>
</th>
)
}
},
/** /**
* 将父组件的columns进行处理:增加设置列按钮 * 将父组件的columns进行处理:增加设置列按钮
* 冻结列要有width,否则会有问题,建议使用minWidthscroll.x要大于所有列width的和
*/ */
setResultColumns () { setResultColumns () {
// 深度克隆,防止直接修改父组件数据 // 深度克隆,防止直接修改父组件数据
const columns = cloneDeep(this.columns) const columns = cloneDeep(this.columns)
// 设置按钮插槽配置 // 设置按钮插槽配置
const settingOption = { const settingOption = {
scopedSlots: { filterDropdown: 'settingDropdown',
filterDropdown: 'settingDropdown', filterIcon: 'settingIcon'
filterIcon: 'settingIcon',
customRender: 'action'
}
} }
const findActionIndex = columns.findIndex(col => col && (getKey(col) === actionKey)) let findActionIndex = columns.findIndex(col => col && (getKey(col) === actionKey))
// 如果找到操作栏,就把设置加到操作栏上 // 将设置按钮放到表格右上角,如果有操作栏就固定到右侧(操作栏固定右侧,没有的话就最后一列)
if (findActionIndex !== -1) { if (findActionIndex === -1) {
// 添加设置插槽配置,并固定右侧 findActionIndex = columns.length - 1
Object.assign(columns[findActionIndex], settingOption, { fixed: 'right' }) }
if (columns[findActionIndex].scopedSlots instanceof Object) {
Object.assign(columns[findActionIndex].scopedSlots, settingOption)
} else { } else {
// 如果没有找到操作栏,就把最后列加上设置插槽配置 columns[findActionIndex].scopedSlots = settingOption
Object.assign(columns[columns.length - 1], settingOption)
} }
// 最后过滤掉需要隐藏的字段,按定位进行排序 // 最后过滤掉需要隐藏的字段,按定位进行排序
const startArr = [] // 冻结左侧的列 const startArr = [] // 冻结左侧的列
@@ -180,16 +279,20 @@ export default {
const fixed = this.settingColumnsObj.freeze.includes(key) const fixed = this.settingColumnsObj.freeze.includes(key)
col.hide = this.settingColumnsObj.hide.includes(key) col.hide = this.settingColumnsObj.hide.includes(key)
col.fixed = key === actionKey ? 'right' : fixed col.fixed = key === actionKey ? 'right' : fixed
// 如果是字符串就转换成数字(因为实现拖拽,单位只能是px)
col.width = parseInt(col.width + '')
// 如果没有最小宽度就获取统一设置的最小宽度
col.minWidth = parseInt(col.minWidth + '') || this.columnMinWidth
if (!col.hide) { if (!col.hide) {
// 如果没有宽度就取minWidth(不添加原数据的width属性,这里只对需要固定的minWidth生效) // 如果没有宽度就取minWidth(不添加原数据的width属性,这里只对需要固定的minWidth生效)
const minWidth = col.width || col.minWidth const width = col.width || col.minWidth
switch (col.fixed) { switch (col.fixed) {
case true: case true:
case 'left': case 'left':
startArr.push({ ...col, width: minWidth }) startArr.push({ ...col, width })
break break
case 'right': case 'right':
endArr.push({ ...col, width: minWidth }) endArr.push({ ...col, width })
break break
default: default:
midArr.push(col) midArr.push(col)
@@ -208,7 +311,7 @@ export default {
*/ */
changeSetting (text, type, record) { changeSetting (text, type, record) {
const checked = !text // text是点击前的状态,取反就是要修改的状态 const checked = !text // text是点击前的状态,取反就是要修改的状态
console.log('修改了配置', checked, type, record) // console.log('修改了配置', checked, type, record)
// 修改当前行配置 // 修改当前行配置
record[type] = !checked record[type] = !checked
// 勾选就添加,取消就删除 // 勾选就添加,取消就删除
@@ -234,10 +337,10 @@ export default {
}) })
}, },
// 初始化配置,从columns里获取 // 初始化配置,从columns里获取
initSetting () { initSetting (columns) {
const hide = [] const hide = []
const freeze = [] const freeze = []
this.columns.forEach(col => { columns.forEach(col => {
const key = getKey(col) const key = getKey(col)
// hide属性控制隐藏 // hide属性控制隐藏
if (col.hide) { if (col.hide) {
@@ -263,10 +366,15 @@ export default {
Vue.ls.set(J_TABLE_KEYS, jTableKeys, 7 * 24 * 60 * 60 * 10) Vue.ls.set(J_TABLE_KEYS, jTableKeys, 7 * 24 * 60 * 60 * 10)
Vue.ls.set(saveKey, this.settingColumnsObj, 7 * 24 * 60 * 60 * 10) Vue.ls.set(saveKey, this.settingColumnsObj, 7 * 24 * 60 * 60 * 10)
}, },
// 还原默认配置
resteColumns () {
this.initSetting(this.columnsBak)
},
// 清除本地的配置(当前的JTable) // 清除本地的配置(当前的JTable)
clearSetting () { clearSetting () {
this.settingColumnsObj = { hide: [], freeze: [] } this.settingColumnsObj = { hide: [], freeze: [] }
Vue.ls.remove(this.tableKey + saveSuffix) Vue.ls.remove(this.tableKey + saveSuffix)
this.resteColumns()
this.$message.success('成功清除当前JTable的缓存!') this.$message.success('成功清除当前JTable的缓存!')
}, },
// 清除所有缓存 // 清除所有缓存
@@ -277,23 +385,42 @@ export default {
Vue.ls.remove(key) Vue.ls.remove(key)
}) })
Vue.ls.remove(J_TABLE_KEYS) Vue.ls.remove(J_TABLE_KEYS)
this.resteColumns() // 这里只能刷新当前的表
this.$message.success('成功清除全局JTable的缓存!') this.$message.success('成功清除全局JTable的缓存!')
}, }
}, },
mounted () { mounted () {
// 备份默认配置
this.columnsBak = cloneDeep(this.columns)
const settingColumnsObj = Vue.ls.get(this.tableKey + saveSuffix) const settingColumnsObj = Vue.ls.get(this.tableKey + saveSuffix)
// 第一次进页面或清空缓存进行初始化 // 第一次进页面或清空缓存进行初始化
if (settingColumnsObj) { if (settingColumnsObj) {
this.settingColumnsObj = settingColumnsObj this.settingColumnsObj = settingColumnsObj
} else { } else {
this.initSetting() this.initSetting(this.columns)
} }
}, },
created () { created () {
} }
} }
</script> </script>
<style lang='less' scoped> <style lang="less">
.j-table {
.resize-table-th {
position: relative;
.table-draggable-handle {
transform: none !important;
position: absolute !important;
height: 100% !important;
bottom: 0;
left: auto !important;
right: -5px;
//width: 10px !important;
cursor: col-resize;
touch-action: none;
}
}
}
</style> </style>
@@ -0,0 +1,216 @@
# JTable 支持列自定义及可拖拽列宽的表格
## JTable参数配置
| 参数 | 类型 | 必填 | 说明 |
|--------------|--------|-----|----------------------------------------------------------------|
| tableKey | String | ✔ | 全局`JTable`唯一,持久化存储自定义列配置 |
| columns | Array | ✔ | **需要配合`.sync`获取最新的数据**,具体项见下表 |
| settingStyle | Object | | 自定义列配置表的样式 |
| settingScroll | Object | | 自定义列配置表的滚动配置 |
| scroll | Object | | 表格滚动配置,建议使用拖拽属性`resizable`时设置`scroll.x`**需要配合`.sync`获取最新的数据** |
| columnMinWidth | Number | | 所有列共用的最小宽度,在没有`width``minWidth`时的冻结列和拖拽列的最小宽度 |
## columns参数配置
| 参数 | 类型 | 必填 | 说明 |
|-------------------|----------------|----|--------------------------------|
| hideSettingColumn | Boolean | | 是否在自定义列配置表中隐藏 |
| disabledHide | Boolean | | 是否禁用自定义列配置表中的隐藏复选框 |
| disabledFreeze | Boolean | | 是否禁用自定义列配置表中的冻结复选框 |
| fixed | String、Boolean | | 默认的冻结列,只能为`true``'left'`其他不生效 |
| width | Number | | 列宽,只能是数字 |
| minWidth | Number | | 最小列宽,只能是数字,在冻结列和拖拽列时生效 |
| resizable | Boolean | | 是否启用拖拽,需要表格显示边框`bordered` |
## JTable的方法
### clearAllCacheSetting
用于清理所有JTable的缓存
- `参数:`
- `返回值:`
### clearSetting
用于清理当前表的缓存
- `参数:`
- `返回值:`
### resteColumns
还原初始的配置
- `参数:`
- `返回值:`
## FAQ
### 方法如何调用?
在[示例](#示例)中,设定了一个 `ref="table"` 的属性,那么在vue中就可以使用`this.$refs.table`获取到该表格的实例,并调取其中的方法。
假如我要调取`resteColumns`方法,就可以这么写:`this.$refs.table.resteColumns()`
### columns和scroll为什么要使用`.sync`
保证父组件和子组件数据同步
`columns`自定义列配置后会同步,
`scroll`拖拽后会把最新的总宽度同步
### 对原ATable的使用有哪些限制
- 操作列的`dataIndex``key`必须为`action`
- 带有设置的列不能使用`scopedSlots.filterIcon``scopedSlots.filterDropdown`
- `scroll.x``width`必须是数字,不支持百分比
### 注意事项
- 固定头和列(ant-design-vue自带的问题) :若列头与内容不对齐或出现列重复,请指定固定列的宽度 width。如果指定 width 不生效或出现白色垂直空隙,请尝试建议留一列不设宽度以适应弹性布局,或者检查是否有超长连续字段破坏布局。
建议指定 scroll.x 为大于表格宽度的固定值。注意,且非固定列宽度之和不要超过 `scroll.x`
- `table-key`该属性为全局每个表的唯一属性,建议使用路由+命名的方式,如[示例](#示例)中设置
## 示例
```vue
<template>
<div>
<a-button @click="resetTable">重置表格配置</a-button>
<a-button @click="clearTableCache">清空本表缓存</a-button>
<a-button @click="clearAllTableCache">清空全局JTable缓存</a-button>
<j-table bordered
:row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
:table-key="$route.name + '_table'"
ref="table"
rowKey="key"
:data-source="dataSource"
:scroll.sync="scroll"
:columns.sync="columns">
<span slot="action" slot-scope="{record}">
<a-popconfirm
v-if="dataSource.length"
title="是否删除?"
@confirm="() => onDelete(record.key)"
>
<a href="javascript:">Delete</a>
</a-popconfirm>
</span>
</j-table>
</div>
</template>
<script>
import JTable from '@comp/jero/JTable'
export default {
name: 'Demo',
components: { JTable },
data () {
const columns = [
{
// 是否在配置表中隐藏
// hideSettingColumn: true,
// 尽量都设置最小宽度,冻结列与拖拽时生效
minWidth: 100,
width: 100,
// 禁用配置表中的隐藏或冻结
disabledHide: true,
disabledFreeze: true,
// 可拖拽属性(不能fixed一起用)
// resizable: true,
// 默认冻结,值可以是 'left' 或 true
fixed: true,
title: '#',
ellipsis: true,
dataIndex: 'key',
},
{
resizable: true,
title: 'Date',
dataIndex: 'date',
width: 200
},
{
resizable: true, // 可拖拽属性
title: 'Amount',
dataIndex: 'amount',
minWidth: 100,
width: 100
},
{
title: 'Type',
dataIndex: 'type',
width: 100
},
{
title: 'Note',
dataIndex: 'note'
// 保留一列自适应
// width: 100
},
{
title: 'Action',
key: 'action',
width: 200,
// filterIcon 和 filterDropdown 不能使用
scopedSlots: { customRender: 'action' }
}
]
const dataSource = [
{
key: 0,
date: '2018-02-11',
amount: 120,
type: 'income',
note: 'transfer'
},
{
key: 1,
date: '2018-03-11',
amount: 243,
type: 'income',
note: 'transfer'
},
{
key: 2,
date: '2018-04-11',
amount: 98,
type: 'income',
note: 'transfer'
}
]
return {
scroll: { x: 1000 },
columns: columns,
dataSource: dataSource,
selectedRowKeys: []
}
},
methods: {
// 还原表格初始配置
resetTable() {
this.$refs.table.resteColumns()
},
// 清除当前表格缓存
clearTableCache () {
this.$refs.table.clearSetting()
},
// 清除所有缓存
clearAllTableCache () {
this.$refs.table.clearAllCacheSetting()
},
onDelete (key) {
this.$message.info(`del:${key}`)
},
onSelectChange (selectedRowKeys) {
console.log('selectedRowKeys changed: ', selectedRowKeys)
this.selectedRowKeys = selectedRowKeys
}
}
}
</script>
```
+51 -53
View File
@@ -1,51 +1,29 @@
<template> <template>
<a-card :bordered="false"> <a-card :bordered="false">
<div> <div>
<div> <div style="margin-bottom: 5px;">
<a-button @click="clearCurrentCache(1)">清理表1缓存</a-button> <a-button @click="resetTable">重置表格配置</a-button>
<a-button @click="clearCurrentCache(2)">理表2缓存</a-button> <a-button @click="clearTableCache" style="margin-left: 5px;">空本表缓存</a-button>
<a-button @click="clearJTableCache">全局缓存</a-button> <a-button @click="clearAllTableCache" style="margin-left: 5px;">全局JTable缓存</a-button>
</div> </div>
<j-table bordered <j-table bordered
:table-key="$route.name + '_table1'" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
ref='table1' :table-key="$route.name + '_table'"
rowKey='key' ref="table"
tableLayout='fixed' rowKey="key"
:scroll="{ x: 2000 }"
:data-source="dataSource" :data-source="dataSource"
:scroll.sync="scroll"
:columns.sync="columns"> :columns.sync="columns">
<span slot="action" slot-scope="{record}"> <span slot="action" slot-scope="{record}">
<a-popconfirm <a-popconfirm
v-if="dataSource.length" v-if="dataSource.length"
title="Sure to delete?" title="是否删除?"
@confirm="() => onDelete(record.key)" @confirm="() => onDelete(record.key)"
> >
<a href="javascript:">Delete</a> <a href="javascript:">Delete</a>
</a-popconfirm> </a-popconfirm>
</span> </span>
</j-table>
<j-table bordered
:table-key="$route.name + '_table2'"
ref='table2'
rowKey='key'
tableLayout='fixed'
:scroll="{ x: 2000 }"
:data-source="dataSource"
:columns.sync="columns">
<span slot="action" slot-scope="{record}">
<a-popconfirm
v-if="dataSource.length"
title="Sure to delete?"
@confirm="() => onDelete(record.key)"
>
<a href="javascript:">Delete</a>
</a-popconfirm>
</span>
</j-table> </j-table>
</div> </div>
@@ -61,42 +39,52 @@ export default {
data () { data () {
const columns = [ const columns = [
{ {
// 是否在配置表格中显示 // 是否在配置表中隐藏
// hideSettingColumn: true, // hideSettingColumn: true,
// 尽量要有minWidth,冻结列时会临时使用作为width // 尽量都设置最小宽度,冻结列与拖拽时生效
minWidth: 100, minWidth: 100,
// 禁用配置表格中的隐藏或冻结 width: 100,
// disabledHide: true, // 禁用配置表中的隐藏或冻结
// disabledFreeze: true, disabledHide: true,
disabledFreeze: true,
// 可拖拽属性(不能fixed一起用)
// resizable: true,
// 默认冻结,值可以是 'left' 或 true
fixed: true,
title: '#', title: '#',
ellipsis: true, ellipsis: true,
dataIndex: 'key', dataIndex: 'key'
fixed: true
}, },
{ {
resizable: true,
title: 'Date', title: 'Date',
dataIndex: 'date', dataIndex: 'date',
minWidth: 200 width: 200
}, },
{ {
resizable: true, // 可拖拽属性
title: 'Amount', title: 'Amount',
dataIndex: 'amount', dataIndex: 'amount',
minWidth: 100 minWidth: 100,
width: 100
}, },
{ {
title: 'Type', title: 'Type',
dataIndex: 'type', dataIndex: 'type',
minWidth: 100 width: 100
}, },
{ {
title: 'Note', title: 'Note',
dataIndex: 'note', dataIndex: 'note'
minWidth: 100 // 保留一列自适应
// width: 100
}, },
{ {
title: 'Action', title: 'Action',
key: 'action', key: 'action',
width: 200 width: 200,
// filterIcon 和 filterDropdown 不能使用
scopedSlots: { customRender: 'action' }
} }
] ]
const dataSource = [ const dataSource = [
@@ -123,26 +111,36 @@ export default {
} }
] ]
return { return {
columns, scroll: { x: 1400 },
dataSource columns: columns,
dataSource: dataSource,
selectedRowKeys: []
} }
}, },
methods: { methods: {
// 还原表格初始配置
resetTable () {
this.$refs.table.resteColumns()
},
// 清除当前表格缓存 // 清除当前表格缓存
clearCurrentCache (n) { clearTableCache () {
this.$refs['table' + n].clearSetting() this.$refs.table.clearSetting()
}, },
// 清除所有缓存 // 清除所有缓存
clearJTableCache () { clearAllTableCache () {
this.$refs.table1.clearAllCacheSetting() this.$refs.table.clearAllCacheSetting()
}, },
onDelete (key) { onDelete (key) {
this.$message.info(`del:${key}`) this.$message.info(`del:${key}`)
},
onSelectChange (selectedRowKeys) {
console.log('selectedRowKeys changed: ', selectedRowKeys)
this.selectedRowKeys = selectedRowKeys
} }
} }
} }
</script> </script>
<style scoped> <style lang='less' scoped>
@import '~@assets/less/common.less';
</style> </style>