vue场景——记录滚动高度

2020-07-13  本文已影响0人  张先觉

#思路:

路由跳转之前(或是Tab切换之前),记录一个高度值Value。之后,控制其滚动scrollTo(0, value),即可。

#知识点

#代码

<template>
    <div>
        <div class="about-content" ref="about"></div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            scrollHeight: 0,    // 记录滚动高度
        };
    },
    mounted() {
        this.aboutUs();
    },
    activated(){
        // 等到DOM更新完成之后,然后,执行this.$nextTick,类似于Promise then()
        this.$nextTick(() => {
            this.$refs.about.scrollTo(0, this.scrollHeight);
        })
    },
    beforeRouteLeave(to, from, next) {
        this.scrollHeight = this.$refs.about.scrollTop;
        next();
    },
};
</script>

<style scoped>
    .about-content{
        padding: 10px; background: #fff;
        overflow: auto;
        height: calc(100vh - 1.2rem); 
        -webkit-overflow-scrolling: touch;
    }

</style>
<template>
    <div>
        <nav>
            <div :class="{'nav-item':true, 'active':isShow}" @click="navClickToggle(1)">盒子1</div>
            <div :class="{'nav-item':true, 'active':!isShow}" @click="navClickToggle(2)">盒子2</div>  
        </nav>

        <main class="main" ref="main">
            <!-- 盒子1 -->
            <section v-show="isShow"> </section>

            <!-- 盒子2 -->
            <section v-show="!isShow"></section>
        </main>
    </div>
</template>

<script>
export default {
    name: "Start",
    data() {
        return {
            isShow: true,
            mainScrollHeight:"",
            currentScrollHeight:0,
            willScrollHeight:0,
            
        }
    },
    activated: function () {
        // 记录滚动位置
        this.$refs.main.scrollTo(0,this.mainScrollHeight)
    },
    beforeRouteLeave(to, from, next) {
        this.mainScrollHeight = this.$refs.main.scrollTop;
        next();
    },
    methods: {
        /**
         *  导航栏点击切换,于此同时,记录滚动位置
         * @param flag 1子盒子   2子盒子
         */
        navClickToggle(flag) {
            this.isShow = !this.isShow;
            this.mainScrollHeight = this.$refs.main.scrollTop;
            if(flag === 1){
                this.$nextTick(function(){  
                    this.currentScrollHeight = this.mainScrollHeight;
                    this.$refs.main.scrollTo(0,this.willScrollHeight)
                })  
                
            }else if(flag === 2){
                this.$nextTick(function(){
                    this.willScrollHeight = this.mainScrollHeight;
                    this.$refs.main.scrollTo(0,this.currentScrollHeight);
                })
                
            }
        },
    },
}  
</script>

<style lang="scss" scoped>
.main {
    height: calc(100vh - 2.4rem);
    height: -moz-calc(100vh - 2.4rem);
    height: -webkit-calc(100vh - 2.4rem);
    overflow: auto;
    &::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
}

</style>
上一篇 下一篇

猜你喜欢

热点阅读