如何以编程方式滚动到 v-list 中的特定 v-list-item?
How do I programmatically scroll to a specific v-list-item in v-list?
我正在使用 Vue/Vuetify 并且有一个可滚动的 v-list
:
<v-layout scrollable ...
<v-list ...
<template v-for=id...
<v-list-item :key=id...
是否可以通过编程方式滚动项目,使特定项目位于可滚动列表的可见区域?
您可以使用普通 JavaScript 方法滚动到任何 DOM 元素 scrollIntoView。
在此之前,您可以为列表中的每个元素指定一个 id
。例如,这样:
<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()
}
}
测试这个 at CodePen。
P.S.: v-layout API 中没有 scrollable
道具。至少,在最新的 v2.6.3.
我正在使用 Vue/Vuetify 并且有一个可滚动的 v-list
:
<v-layout scrollable ...
<v-list ...
<template v-for=id...
<v-list-item :key=id...
是否可以通过编程方式滚动项目,使特定项目位于可滚动列表的可见区域?
您可以使用普通 JavaScript 方法滚动到任何 DOM 元素 scrollIntoView。
在此之前,您可以为列表中的每个元素指定一个 id
。例如,这样:
<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()
}
}
测试这个 at CodePen。
P.S.: v-layout API 中没有 scrollable
道具。至少,在最新的 v2.6.3.