vue列表如何自動滾動到制定位置
背景
業(yè)務(wù)開發(fā)中遇到一個需求,是要求跳轉(zhuǎn)到新頁面,并默認(rèn)選中內(nèi)容,如果內(nèi)容在列表的位置靠后,就需要滾動到可見范圍內(nèi)。
實(shí)現(xiàn)
1. 循環(huán)實(shí)現(xiàn)列表,為每個item添加id,**:id="'item' + index"**,方便后續(xù)查找對應(yīng)項(xiàng)
<div v-for="(item,index) in dataList" :id="'item' + index" :key="index" class="item">
<span>item: {{ item.name }}</span>
</div>2. 待列表加載完后,執(zhí)行滾動事件
// count 默認(rèn)選中內(nèi)容的序號
document.getElementById('item' + count).scrollIntoView()知識點(diǎn)
1. scrollIntoView:Element.scrollIntoView() 方法讓當(dāng)前的元素滾動到瀏覽器窗口的可視區(qū)域內(nèi)。
2. 未避免事件執(zhí)行失敗,一定要在頁面加載完成才能觸發(fā)事件,
推薦2種方式
- 2.1 在mounted事件中觸發(fā)
- 2.2 在執(zhí)行事件時,用this.$nextTick保證頁面加載完成
this.$nextTick(() => {
document.getElementById('item' + count).scrollIntoView()
})代碼
以下是一個小demo,可直接執(zhí)行
<template>
<div class="white-body-view">
<div class="content-view">
<div v-for="(item,index) in dataList" :id="'item' + index" :key="index" class="item">
<span>item: {{ item.name }}</span>
</div>
</div>
</div>
</template><script>
export default {
data() {
return {
dataList: [
{
name: '1'
},
{
name: '2'
},
{
name: '3'
},
{
name: '4'
},
{
name: '5'
},
{
name: '6'
},
{
name: '7'
},
{
name: '8'
},
{
name: '9'
},
{
name: '10'
},
{
name: '11'
},
{
name: '12'
}
]
}
},
mounted() {
document.getElementById('item5').scrollIntoView()
}
}
</script><style lang="scss">
.content-view {
height: 200px;
width: 200px;
overflow: auto;
}
.item {
line-height: 40px;
}
</style>總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實(shí)現(xiàn)簡易選項(xiàng)卡功能
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)簡易選項(xiàng)卡功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06
VUE element-ui 寫個復(fù)用Table組件的示例代碼
本篇文章主要介紹了VUE element-ui 寫個復(fù)用Table組件的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
Vue3超詳細(xì)的ref()用法教程(看這一篇就夠了!)
這篇文章主要給大家介紹了關(guān)于Vue3超詳細(xì)的ref()用法的相關(guān)資料,在Vue3中ref函數(shù)不僅可以用于在組件中獲取DOM元素或子組件的引用,還可以直接訪問組件元素本身,需要的朋友可以參考下2023-07-07
this.$router.push攜帶參數(shù)跳轉(zhuǎn)頁面的實(shí)現(xiàn)代碼
這篇文章主要介紹了this.$router.push攜帶參數(shù)跳轉(zhuǎn)頁面,this.$router.push進(jìn)行頁面跳轉(zhuǎn)時,攜帶參數(shù)有params和query兩種方式,本文結(jié)合實(shí)例代碼給大家詳細(xì)講解,需要的朋友可以參考下2023-04-04
Vue3?<script?setup?lang=“ts“>?的基本使用
<script setup>?是在單文件組件 (SFC) 中使用?composition api?的編譯時語法糖,本文主要講解<script setup>?與?TypeScript?的基本使用,感興趣的朋友跟隨小編一起看看吧2022-12-12
vue2.0實(shí)現(xiàn)音樂/視頻播放進(jìn)度條組件
這篇文章主要為大家詳細(xì)介紹了vue2.0實(shí)現(xiàn)音樂和視頻播放進(jìn)度條組件的思路及具體實(shí)現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06
基于express中路由規(guī)則及獲取請求參數(shù)的方法
下面小編就為大家分享一篇基于express中路由規(guī)則及獲取請求參數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

