场景:使用vue+vant做移动端开发,当打开a页面浏览到某个位置,点击跳转到b页面,然后再后退回a页面浏览的那个位置。

 

解决办法:使用store存储滚动条的位置。

 

store存储setScrollY的高度,代码如下:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state:{//设置属性 用来存储数据
        setScrollY: 0,//页面滚动条显示高度
    },
    getters:{//对应方法 用来获取属性的状态
        getScrollY:state => state.setScrollY,
    },
    mutations:{//更改属性的状态
        setScrollYCommit(state, data){
            state.setScrollY = data
        }
    },
    actions:{//应用 mutation
        setScrollYAction({commit}, data){
            commit('setScrollYCommit',data)
        }
    },
})

export default store

在vue页面下,通过refs获取到dom节点,再获取scrollTop则是滚动条高度,例如:ref是scrollRef,则获取的是this.$refs.scrollRef.scrollTop(注意:ref一定是在overflow: auto的标签上)。代码如下:

<template>
    <div class="box_cls">
        <van-nav-bar left-text="浏览" left-arrow @click-left="onClickLeft"/>
        <div class="info_box_cls" ref="scrollRef">
            
            ...此处很多内容省略...
			<!-- 此处跳转到b页面 -->
            <div @click="toBVue"></div>
        </div>
        
    </div>
</template>
<script>
    export default {
        name:"AVue",
        data(){
            return {
            }
        },
        mounted(){
            this.$nextTick(()=>{
            		//获取到store里存储的滚动高度
                let scrollY = this.$store.getters.getScrollY;
                if(scrollY >0){
                		//将高度设值回scrollTop
                    this.$refs.scrollRef.scrollTop = scrollY;
                }
                
            })
        },
        methods:{
            onClickLeft(){
           			//后退
                this.$router.go(-1);
            },
            toBVue(){
                //跳转到b页面,在这获取滚动高度存储到store里
                let scrollY = this.$refs.scrollRef.scrollTop;
                this.$store.dispatch('setScrollYAction',scrollY);
                this.$router.push({path:'/BVue'});
            }
        }
    }
</script>
<style scoped>
    .box_cls{
        width: 100%;
        height: 100%;
    }
    .info_box_cls{
        height: calc(100vh - 64px);
        overflow: auto;
    }      
</style>

到此就能实现后退回原来浏览的位置了。

Logo

前往低代码交流专区

更多推荐