关于前端:解决vuerouter跳转后元素内嵌滚动条自动回到顶部的问题

该路由曾经应用了缓存的前提下

<keep-alive>
    <router-view></router-view>
</keep-alive>
当页面跳转,点击返回按钮后发现之前页面里的一个列表元素的滚动条主动回到顶部了,因为该元素设置了固定的宽高并且css设置overflow: scroll; 这样的话,滚动条不是页面级别的,并没有被记录下来,然而该组件又没有产生扭转,所以封装个组件记录滚动条地位,页面产生扭转就设置会以前的地位就行了。

自定义组件

<template>
<div 
    class="scroll_container"
    ref="ScrollElCp"
    :style="{
        height:height,
        width:width,
    }">
    <slot></slot>
</div>
</template>
<script>
//滚动容器组件(解决页面切换时不记录组件滚东条的状况)
export default {
    name: 'ScrollElCp',
    props:{
        height:String,  //高度
        width:String,  //宽度
    },
    data() {
        return {
            scrollTop:0,
        }
    },
    watch:{
        $route(){
            const ScrollElCp = this.$refs.ScrollElCp;
            if(!ScrollElCp) return;
            ScrollElCp.scrollTop = this.scrollTop;
        },
    },
    mounted(){
        const ScrollElCp = this.$refs.ScrollElCp;
        ScrollElCp.addEventListener('scroll',()=>{
            this.scrollTop = ScrollElCp.scrollTop;
        });
    },
}
</script>
<style scoped lang="scss">
.scroll_container {
    overflow: scroll;
}
</style>
应用办法
<template>
<div>
    <ScrollElCp
        height="100px"
        width="100px">
        <h1
            v-for="(item,index) in 100"
            :key="index">
            {{item}}
        </h1>
    </ScrollElCp>
</div>
</template>
<script>
import ScrollElCp from "@/components/public/ScrollEl";
export default {
    components: {
        ScrollElCp,
    },
}
</script>
<style scoped lang="scss">

</style>
这样只是组件原本就有缓存的状况,如果没有的话能够将该组件的滚动地位全局记录下来,不过这样很麻烦,需要的话请谷歌看看吧。

原文地址

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理