thoni56
thoni56

Reputation: 3335

How do I programmatically scroll to a specific v-list-item in v-list?

I'm using Vue/Vuetify and have a v-list that is scrollable:

<v-layout scrollable ...
  <v-list ...
    <template v-for=id...
      <v-list-item :key=id...

Is it possible to programmatically scroll the items so that a particular one is in the visible area of the scrollable list?

Upvotes: 3

Views: 5463

Answers (1)

Alexander Shkirkov
Alexander Shkirkov

Reputation: 3857

You can scroll to any DOM element using plain JavaScript method scrollIntoView.

Before that you can give an id for each element of your list. By example, this way:

<v-container>
  <v-row>
    <v-col>
      <v-btn
        ref="button"
        block
        color="primary"
        @click="scrollTo"
      >
        scroll to Item-20
      </v-btn>
    </v-col>
    
    <v-col cols="12">
      <v-card>
        <v-list max-height="300" class="overflow-y-auto">
          <v-subheader>ITEMS</v-subheader>
          <v-list-item
             v-for="(item, i) in items"
             :key="i"
             :id="'list-item-' + (item.id + 1)">
            <v-list-item-content>
              <v-list-item-title v-text="item.text"></v-list-item-title>
            </v-list-item-content>
          </v-list-item>
        </v-list>
      </v-card>
    </v-col>
  </v-row>
</v-container>
...
data () {
  return {
    items: [],
  }
},
mounted() {
  for (let i = 0; i < 50; i++) {
    this.items.push({ id: i, text: 'Item-' + (i + 1)})
  }
},
methods: {
  scrollTo() {
    document.getElementById("list-item-20").scrollIntoView()
  }
}

Test this at CodePen.

P.S.: there is no scrollable prop in v-layout API. At least, in latest v2.6.3.

Upvotes: 4

Related Questions