在a-table的基础上实现拖拽功能 (封装的组件)

/*在vue components文件下 添加一个组件文件 AntTable
AntTable下新建一个index.js文件
使用该组件时 只需要在.vue页面引入即可  引入方式/使用方式请参考下面代码*/

<template>
  <div>
    <ant-table
                    bordered
                    size="small"
                    :row-key="key"
          :rowSelection="{
                        columnWidth: 50,
                        selectedRowKeys: selectedRowKeys,
                        onChange: onSelectChange,
                    }"
                    :pagination="pagination"
                    :change="handleTableChange"
                    :scroll="{ x: 1500 }"
                    :dataColumns="columns"
                    :dataSource="data"
                    :loading="tableLoading"
                >
        bordered      是否展示外边框和列边框
        size          设置表格大小
        :row-key      表格行 key 的取值,可以是字符串或一个函数
        :rowSelection 列表项是否可选择(添加复选框)
            columnWidth  设置复选框的宽度
            selectedRowKeys  获取当前复选框选中的 key值
            onChange  改变复选框是否选中事件

        :pagination   分页器
        :change       分页、排序、筛选变化时触发
        :scroll       设置横向或纵向滚动
        :dataColumns  表格列的配置描述
        :dataSource   数据数组
        :loading      页面是否加载中    
                </ant-table>
  </div>
</template>
<script>
import { AntTable } from '@/components'
export default{
  components:{AntTable},
  data(){
    return{
      // 表格加载显示隐藏控制
            tableLoading: false,
      // 表格数据源
      data: [],
      // 表头数据存放(使用width时千万不要加PX)
      columns:[],
      // 分页对象
            pagination: {
                current: 1, // 当前页码
                total: 0,   // 数据总条数
                pageSize: 10, //每页中显示10条数据
                pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
                showTotal: total => `当前共有${total}条数据`, //分页中显示总的数据
                showQuickJumper: true, // 是否可以改变 pageSize
                showSizeChanger: true, // 是否可以跳转到指定页
      },
      // 表格选择行的key数据
            selectedRowKeys: [],
            // 表格所选择的行数据
            selectedRows: [],
    }
  },
  methods: {
    // 表格复选框选中数据
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
    },
    // 表格分页
        handleTableChange(page) {
            const pager = { ...this.pagination }
            pager.current = page.current
            pager.pageSize = page.pageSize
            this.pagination = pager
            // this.loadData()  这是刷新表格数据请求  // 按项目需求来
    },
    loadData() {
            this.tableLoading = true
            let params = {
        // 如有其它查询参数可以放进来
                current: this.pagination.current,
                size: this.pagination.pageSize,
      }
      // querySchedulePage  是我查询表格数据的方法
            querySchedulePage(params)
                .then(res => {
                    let { total, list } = res
                    this.data = list
                    this.pagination.total = total
                    this.selectedRowKeys = []
                    this.selectedRows = []
                    this.tableLoading = false
                })
                .catch(() => {
                    this.tableLoading = false
                })
        },
  },
}
</script>
*/




//#region 只需要复制下面代码 上面文字只做说明

import 引入not Found 就去安装依赖
import T from 'ant-design-vue/es/table/Table'
import Vue from 'vue'              // 可以放到main.js文件
import VueDraggableResizable from 'vue-draggable-resizable' // 可以放到main.js文件
Vue.component('vue-draggable-resizable', VueDraggableResizable) // 可以放到main.js文件
import get from 'lodash.get'
const draggingMap = {}
const draggingState = Vue.observable(draggingMap)
import enUS from 'ant-design-vue/es/locale/en_US';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import { LocaleResources } from '@/utils/sessionStore'  // 项目国际化判断 没有要求可以删掉

export default {
    data() {
        this.handleComponents = {
            header: {
                cell: (h, props, children) => {
                    let thDom = null
                    const { key, ...restProps } = props
                    const col = this.dataColumns.find(item => {
                        const k = item.dataIndex || item.key
                        return k === key
                    })
                    if (!col || !col.width) {
                        return <th {...restProps}>{children}</th>
                    }
                    const onDrag = x => {
                        draggingState[key] = 0
                        col.width = Math.max(x, 20)
                    }

                    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.key}
                                class="table-draggable-handle"
                                w={10}
                                x={draggingState[key] || col.width}
                                z={1}
                                axis="x"
                                draggable={true}
                                resizable={false}
                                onDragging={onDrag}
                                onDragstop={onDragstop}
                            ></vue-draggable-resizable>
                        </th>
                    )
                },
            },
        }
        return {
            needTotalList: [],
            selectedRows: [],
            selectedRowKeys: [],
        }
    },
    props: Object.assign({}, T.props, {
        alert: {
            type: Boolean,
            default: false,
        },
        rowKey: {
            type: [String, Function],
            default: 'key',
        },
        dataSource: {
            type: Array,
            required: true,
        },
        rowSelection: {
            type: Object,
            default: null,
            required: false,
        },
        dataColumns: {
            type: Array,
            default: true,
        },
        change: {
            type: Function,
            required: true,
        }
    }),
    methods: {
        updateSelect(selectedRowKeys, selectedRows) {
            this.selectedRows = selectedRows
            this.selectedRowKeys = selectedRowKeys
            const list = this.needTotalList
            this.needTotalList = list.map(item => {
                return {
                    ...item,
                    total: selectedRows.reduce((sum, val) => {
                        const total = sum + parseInt(get(val, item.dataIndex))
                        return isNaN(total) ? 0 : total
                    }, 0)
                }
            })
        },
    },
    render() {
        const props = {}
        const localKeys = Object.keys(this.$data)

        Object.keys(T.props).forEach(k => {
            const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
            if (localKeys.includes(localKey)) {
                props[k] = this[localKey]
                return props[k]
            }

            this[k] && (props[k] = this[k])
            return props[k]
        })
        // const columns = this.dataColumns.forEach(col => {
        //     draggingMap[col.key] = col.width
        // })
        // 设置表格多语言
        let locale = LocaleResources() === 'zh-CN' ? zhCN : enUS
        const table = (
            <a-config-provider class="element-top"
                locale={locale}>
                <a-table
                    components={this.handleComponents}
                    rowSelection={this.rowSelection}
                    columns={this.dataColumns}
                    dataSource={this.data}
                    onChange={this.change}
                    {...{ props, scopedSlots: { ...this.$scopedSlots } }}
                    onExpand={(expanded, record) => {
                        this.$emit('expand', expanded, record)
                    }}
                >
                    {Object.keys(this.$slots).map(name => (
                        <template slot={name}>{this.$slots[name]}</template>
                    ))
                    }

                    {this.dataColumns.map((item, index) => (
                        <template slot={item.slotName}>
                            <span key={index}>{this.$t(item.scopedSlots.title)}</span>
                        </template>
                    ))
                    }

                </a-table>
            </a-config-provider>
        )

        return <div class="table-wrapper">
            {table}
        </div>
    },
}
//#endregion

 

posted on 2021-01-25 11:34  ㅤㅤㅤㅤㅤㅤ  阅读(1463)  评论(0编辑  收藏  举报

导航