Currently, I am working on a project using Vue. On the user's homepage, there is a list of posts that are displayed. When the user clicks on "show full post," the list of posts is replaced by an expanded view of the single post.
However, a challenge arises when the user wants to go back to see the list of posts. The page automatically scrolls back to the top, regardless of where the user was previously scrolled to.
My goal is to have the page return to the exact point where the user was before clicking on "view full post."
To tackle this issue, I have implemented a solution where I store the current scroll position value when "show full post" is clicked. Then, when the user clicks on the back button, I use window.scrollTo to return to that position.
While this solution works the first time, it encounters issues in subsequent attempts as it always returns to the position of the first time.
I suspect that this problem may be related to Vue caching the function, but I am unsure of how to address it.
<template>
<div>
<post-list @showFullPost="showFullPost($event)" v-show="!showingFullPost"></post-list>
<full-post @goBack="showAllPosts" v-if="showingFullPost"></full-post>
</div>
</template>
<script>
export default{
data: function(){
return {
currentHeight: 0,
showingFullPost: false
}
},
methods:{
showFullPost(post){
this.currentHeight = window.scrollY;
//other code
},
showAllPosts(){
//some code
window.scrollTop(0, this.currentHeight); //this only works the first time and subsequently goes to the position of the first time
}
}
}
</script>