The effect

1. Method 1

Record the scrollbar position when clicking, store it locally and enter the route again to read the scrollhop position

1. Save the route into the Scroll when redirecting

  • If you want to have more than one page, you can also save the name, which defaults to one page
    methods: {
      go() {
        console.log(document.documentElement.scrollTop)
        localStorage.setItem("scroll".document.documentElement.scrollTop)
        this.$router.push({path: '/'}}})Copy the code

1. 2 Read the scroll position

  • When entering the route again, the scroll position is selected from the local

ScrollBehaviors are configured in router/index.js using scrollBehaviors

const router = new VueRouter({
  mode: 'hash',
  routes,
  scrollBehavior(to, from){
    if(to.name==='fatherSlot') {// Name indicates the route name
      return {x:0.y: parseInt(localStorage.getItem('scroll'))}// Read the local scroll
    }
    console.log("to",to,"from".from)}})Copy the code

2. Method two

Using Vue’s keep-alive, using the caching mechanism to record the scrollbar position, but there is a disadvantage, the page is not recorded after the refresh, but simple and efficient

2. 1 Configure the routes to be cached

  • The cachepageA.pageB, the code is the same, as in the demo diagram.pageA.pageCIs the name of the component.

html

    <keep-alive :include="['pageA','pageC']">
      <router-view/>
    </keep-alive>
Copy the code

2. 2 Record the scroll position in the route

javascript

    data() {
      return {
        curScrollTop: 0 // Record the scrollbar position object}},// This hook function fires repeatedly. It is a keep-alive hook function
    activated() {
      document.documentElement.scrollTop = this.curScrollTop || 0
    },
    // When the route leaves, the hook function saves
    beforeRouteLeave (to, from, next) {
      this.curScrollTop = document.documentElement.scrollTop || 0
      next()
    },
Copy the code