vue列表如何自動滾動到制定位置
背景
業(yè)務開發(fā)中遇到一個需求,是要求跳轉到新頁面,并默認選中內容,如果內容在列表的位置靠后,就需要滾動到可見范圍內。
實現(xiàn)
1. 循環(huán)實現(xiàn)列表,為每個item添加id,**:id="'item' + index"**,方便后續(xù)查找對應項
<div v-for="(item,index) in dataList" :id="'item' + index" :key="index" class="item"> <span>item: {{ item.name }}</span> </div>
2. 待列表加載完后,執(zhí)行滾動事件
// count 默認選中內容的序號 document.getElementById('item' + count).scrollIntoView()
知識點
1. scrollIntoView:Element.scrollIntoView() 方法讓當前的元素滾動到瀏覽器窗口的可視區(qū)域內。
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>
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
VUE element-ui 寫個復用Table組件的示例代碼
本篇文章主要介紹了VUE element-ui 寫個復用Table組件的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11this.$router.push攜帶參數跳轉頁面的實現(xiàn)代碼
這篇文章主要介紹了this.$router.push攜帶參數跳轉頁面,this.$router.push進行頁面跳轉時,攜帶參數有params和query兩種方式,本文結合實例代碼給大家詳細講解,需要的朋友可以參考下2023-04-04Vue3?<script?setup?lang=“ts“>?的基本使用
<script setup>?是在單文件組件 (SFC) 中使用?composition api?的編譯時語法糖,本文主要講解<script setup>?與?TypeScript?的基本使用,感興趣的朋友跟隨小編一起看看吧2022-12-12