Vuetify数据表格中的滚动固定表头

5
当Vuetify数据表格的高度大于窗口高度时,当我们滚动页面时,我希望表头行在数据表格滚动完成前保持固定状态。
行为应与此类似: https://output.jsbin.com/zuzuqe/1/ 也像他们使用的数据表格一样: https://www.worldometers.info/coronavirus/ 我还尝试过:
th {
    position:sticky;  
    top: 0;
    background-color: white;
}

position: sticky与datatable相对而非窗口相关

有人可以给我一些关于如何在Vuetify datatable上实现相同效果的想法或codepen吗?

4个回答

1

1
fixed-header 只能用于使表格级别内的标题行固定。它不会在滚动页面时固定,可以查看此演示 https://output.jsbin.com/zuzuqe/1/ - chans

1

1

您可以使用Vue组件 Float Thead vue component来完成此操作。

编辑: 这是可用于Vuetify的Vue指令v-simple-table

用法:

<v-simple-table v-simple-table-sticky></v-simple-table>

指令:

function stickyScrollHandler(el) {
    return () => {
        const getOffsetTop = function(element) {
            let offsetTop = 0;
            while (element) {
                offsetTop += element.offsetTop;
                element = element.offsetParent;
            }
            return offsetTop;
        }

        const table = el.querySelector("table");
        const tableHeader = el.querySelector(".adx-table_sticky_header");
        let tableHeaderFloat = el.querySelector(".adx-table_sticky--float");

        const pos = getOffsetTop(table) - window.scrollY;

        if (pos < 0) {
            if (!tableHeaderFloat) {
                const clone = tableHeader.cloneNode(true);
                clone.classList.remove('.table_sticky_header');

                tableHeaderFloat = document.createElement('table');
                tableHeaderFloat.appendChild(clone);
                tableHeaderFloat.classList.add("adx-table_sticky--float");
                table.parentNode.appendChild(tableHeaderFloat);

                tableHeader.style.opacity = 0;
            }

            if (Math.abs(pos) < table.offsetHeight - tableHeaderFloat.offsetHeight) {
                tableHeaderFloat.style.position = "absolute";
                tableHeaderFloat.style.top = Math.abs(pos) + "px";
            }
        } else {
            if (tableHeaderFloat) {
                tableHeaderFloat.remove();
            }

            tableHeader.style.opacity = 1;
        }
    }
}

Vue.directive("simple-table-sticky", {
    bind: function(el, binding, vnode) {
        el.querySelector("table thead").classList.add("adx-table_sticky_header");
        el.style.position = "relative"

        window.addEventListener('scroll', stickyScrollHandler(el));
    },
    unbind: function(el) {
        window.removeEventListener('scroll', stickyScrollHandler(el));
    }
});

这是一个不同的库,我已经使用vuetify datatable实现了datatable的所有功能。如果有任何CSS修复,请建议使用vuetify本身。这将非常有帮助来解决这个问题。 - chans

0
之前的回答结合起来对我有用:
像loomchild建议的那样,在表格包装器上取消overflow属性:
:deep(div.v-table__wrapper) {
  overflow: unset
}

并根据Enkhtulga的建议,将fixed-header添加到组件中(在这种情况下,不需要在thead上设置position/top,此属性会自动处理)。
<v-data-table fixed-header>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接