【问题标题】:Scroll to a programmatically selected row in a v-data-table滚动到 v-data-table 中以编程方式选择的行
【发布时间】:2020-07-24 19:02:01
【问题描述】:

我有一张地图,上面的地图项也列在 v-data-table 中。当用户单击一行时,该功能会在地图上突出显示。当用户单击地图特征时,会选择相应的网格行。所以我以编程方式设置选定的行,如下所示:

selectRow(id) {
  this.selected = [this.getRowFromId(id)]
},

getRowFromId(id) {
  for (let site of this.sites) {
    if (site.id === id) return site;
  }
  return []
},

适用于一个 UX 问题:表格未滚动到所选行。

我正在使用一个垂直滚动的数据表,所有行都在网格中,而不是分页。

关于如何以编程方式滚动数据表的任何想法?

【问题讨论】:

  • 也许尝试使用 ref 来选择一个元素?

标签: vue.js vuetify.js


【解决方案1】:

这是我的解决方案。我在这篇文章中找到了我想要的大部分内容:Plain JavaScript - ScrollIntoView inside Div

我必须做一些 v-data-grid 特定的事情才能使它工作。我在我的上下文中使用了一个观察者,但你可以在任何你需要的地方:

    watch: { 
      selectedId: function(newVal) { // watch it
        // Select the row
        this.selectRow(newVal)
        // Scroll the item into view
        // First we need to let the component finish selecting the row in the background
        setTimeout( () => {
            // We get the selected row (we assume only one or the first row)
            const row = document.getElementsByClassName("v-data-table__selected")[0]
            // Then we get the parent. We need to give the -v-data-table a ref
            // and we actually take the child of the table element which 
            // has the scrollbar in my case.
            const parent = this.$refs.detailGrid.$el.firstChild
            // Finally call the scroll function
            this.scrollParentToChild(parent, row )
        }, 100)
      }
    },
    methods: {
      scrollParentToChild(parent, child) {
        // Where is the parent on page
        var parentRect = parent.getBoundingClientRect();
        // What can you see?
        var parentViewableArea = {
          height: parent.clientHeight,
          width: parent.clientWidth
        };
        // Where is the child
        var childRect = child.getBoundingClientRect();
        // Is the child viewable?
        var isViewable = (childRect.top >= parentRect.top) && (childRect.top <= parentRect.top + parentViewableArea.height);
        // if you can't see the child try to scroll parent
        if (!isViewable) {
          // scroll by offset relative to parent
          parent.scrollTop = (childRect.top + parent.scrollTop) - parentRect.top - childRect.height
        }
      },
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2021-05-08
    • 2021-07-14
    • 2013-09-01
    相关资源
    最近更新 更多