The route already uses the cache

<keep-alive>
    <router-view></router-view>
</keep-alive>
Copy the code
When the page jumps, click the back button to find that the scroll bar of a list element in the previous page automatically returns to the top because the element has a fixed width and height and the CSS has overflow: Scroll; In this case, the scrollbar is not page-level and is not logged, but the component is cached, so encapsulate a component to record the scrollbar position and set it back to its previous position if the page changes.

Custom Components

<template>
<div 
    class="scroll_container"
    ref="ScrollElCp"
    :style="{ height:height, width:width, }">
    <slot></slot>
</div>
</template>
<script>
// Scroll container components (solve the problem of not recording the component roll east bar during page switching)
export default {
    name: 'ScrollElCp'.props: {height:String./ / height
        width:String./ / width
    },
    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>

Copy the code
Method of use
<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>Copy the code
This is only if the component is already cached. If not, the component’s scroll position can be recorded globally, but this is cumbersome, please Google if necessary.

The original address