The monitor scroll bar resets to 0 when jumping to the page, that is, returns to the top

During the development of the vue project page, sometimes it will appear that when you slide to the middle of the page and jump to other pages, there will be a problem that the page is not displayed from the top. The solution is as follows:

(ps: There is a pit here, if you directly set the scroll position = 0, it may not take effect, then you can use the following method, the personal test is effective)

1. Store a variable scrollEl in the store to record the sliding position of the page before the jump

   computed: {
    
    
   // 同步更新store存的scrollEl记录滚动位置
        scrollEl () {
    
    
            return this.$store.state.scrollEl
        }
    },
    mounted () {
    
    
         // 监听滚动条
        window.addEventListener('scroll', this.scrollMethod, true)
        // 初始化一系列函数
        this.init()
    }, 
    destroyed() {
    
    
        // 销毁时,删除监听滚动事件,否则其他.vue文件也会受影响
        window.removeEventListener('scroll', this.scrollMethod)
    },

2. Use where the current page needs to jump to other pages:

// 先把滚动条回归到顶部,解决跳转至详情,页面未从顶部展示问题 
this.$store.state.scrollEl.target.scrollTop = 0

3. Extension
If you want to restore the position recorded before the jump in the case of Keepalive, you can set a variable to record the last scroll position before the jump, and assign the reverse value to the scroll position stored in the store in activated.

data () {
    
    
	return {
    
    
		currentScroll: 0
	}
}


activated () {
    
    
        this.$store.state.scrollEl.target.scrollTop = this.currentScroll
        
        // 监听滚动条
        window.addEventListener('scroll', this.scrollMethod, true)
    },
methods: {
    
    
	// 跳转前,记录最后的滚动位置
	this.currentScroll = this.$store.state.scrollEl.target.scrollTop
}

end~
I hope the recorded questions can help you, Chirp~

Guess you like

Origin blog.csdn.net/weixin_52443895/article/details/129544784