Keep scroll position when returning to page

陌路散爱 提交于 2021-02-07 14:15:00

问题


I have a long list on page A that I am scrolling through. When I visit another page and later return to page A, I want to be at the scroll position where I left.

I have found this package for Vue (https://github.com/jeneser/vue-scroll-behavior), but I can't get it to work with NuxtJS.

Any advice or ideas on how I best approach this?


回答1:


You can alter the scroll behaviour on route change as described here https://nuxtjs.org/api/configuration-router#scrollBehavior by adapting it in nuxt.config.js. In my case I only apply this to the "/browse" route.

function scrollBehavior (to, from, savedPosition) {
  ...
  if (to.path === '/browse') {
   position = false
  }
  ...
}

We have to set the position to false to retain the scroll position.

To remember the scroll position we can use a package like https://github.com/jeneser/vue-scroll-behavior which we can include as a plugin into nuxt:

import Vue from 'vue'
import vueScrollBehavior from 'vue-scroll-behavior'

export default ({ app }) => {
  Vue.use(vueScrollBehavior, {
    router: app.router
  })
}



回答2:


You can use like this ( You must name it as router.scrollBehavior.js in root to override default behviour settings.),

// router.scrollBehavior.js
export default function(to, from, savedPosition) {
  const defaultPosition = false;
  const scrollTopPosition = { x: 0, y: 0 };

  let position = defaultPosition;
  console.log({ to, from });
  if (savedPosition) {
    position = savedPosition;
  } else if (to.matched.length < 2) {
    position = scrollTopPosition;
  } else if (to.matched.some(child => child.components.default.options.scrollToTop)) {
    position = scrollTopPosition;
  }

  return new Promise(resolve => {
    window.$nuxt.$once('triggerScroll', () => {
      if (to.hash && document.querySelector(to.hash)) {
        position = { selector: to.hash };
      }

      resolve(position);
    });
  });
}



回答3:


/**
 use:
 ```js
  import router from "<you router path>"
  import KeepScroll from "<you code path>"
  Vue.use(KeepScroll, { router })
 ```
and set `keep-scroll-postion` u need save scroll position.
```html
<div v-keep-scroll-postion>
... more
... more
... more
... more
</div>
```
 */

import Router from 'vue-router';
import Vue, { PluginObject } from "vue"

/// keep-alive-scroll-postion-value
const AttributeParamName = "k-l-s-p-v"

/// create custom directive to save scroll position
const configureCustomDirective = () => {
  Vue.directive("keep-scroll-postion", {
    bind: function (el) {
      el.addEventListener("scroll", (event) => {
        const target = event.target as HTMLElement
        if (target === undefined) return
        target.setAttribute(AttributeParamName, target.scrollLeft + '-' + target.scrollTop);
      })
    }
  })
}

interface VueKeepScrollPositionPlugin {
  router: Router
}

const VueKeepScrollPositionPlugin: PluginObject<VueKeepScrollPositionPlugin> = {
  install(vue, option) {
    if (option?.router === undefined) return
    configureCustomDirective()
    const findAndConfigScrollPostion = () => {
      document.querySelectorAll(`[${AttributeParamName}]`).forEach(element => {
        const offset = element.getAttribute(AttributeParamName)?.split("-")
        if (offset === undefined) return
        element.scrollTop = Number.parseFloat(offset[1])
        element.scrollLeft = Number.parseFloat(offset[0])
      })
    }
    option?.router.afterEach(() => vue.nextTick(() => findAndConfigScrollPostion()))
  }
}

export default VueKeepScrollPositionPlugin;

maybe this? https://gist.github.com/0x30/8b850f24b9452d715f356a2df968183f




回答4:


Sometimes you can simply use $router.go(-1) it keeps scroll position when returning to page.




回答5:


Check your CSS and remove the overflow property on your html/body-tag.

html,
body {
    overflow-x: hidden; // 🔥 Remove this
}

Afterwards your scroll position should be saved again.



来源:https://stackoverflow.com/questions/51887512/keep-scroll-position-when-returning-to-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!