S
S
Sergey Nikolaev2020-06-18 13:10:31
JavaScript
Sergey Nikolaev, 2020-06-18 13:10:31

Why is the page not scrolling to the anchor?

Vue app, uses a router, On the main page iterates over an array, rendered with The other page contains components with plain text. At the beginning of each text, a heading with an id with the corresponding item value from the link, which is drawn on the main page. When you click on the link, you go to another page, but scrolling to the location of the "anchor" does not occur. More precisely, the page scrolls only to the middle. If the links are located on the very other page, for example at the top, then the transition through the "anchors" occurs (scrolling to their location).mode: 'history'
router-link:to="{path: '/page', hash: '#'+item}"





I assume that this is due to the fact that the content of the components does not have time to be displayed (fill the space on the page of a certain height equal to the content of the component) by the time the scroll to the "anchor" is triggered.
I also tried to add a method to the router scrollBehavior, no changes were observed.

I would be grateful for any suggestions to implement this task.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Nikolaev, 2020-06-18
@mccrush

As a result, two things helped:
1. Left the method in the router file

scrollBehavior() {
    return { x: 0, y: 0 }
  }

so that during any transitions the page is displayed on top;
2. On the page itself ( /page ) in mounted() I wrote
let elem = document.querySelector(this.$route.hash)
elem.scrollIntoView({ block: 'start', behavior: 'smooth' })

But it's still strange that the solution in the documentation for vue-router didn't want to work for me...
scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      return { selector: to.hash }
    } else {
      return { x: 0, y: 0 }
    }
  }

X
xenonhammer, 2020-06-18
@xenonhammer

normal javascript will help: you need to calculate the position relative to the document, the height of the anchor, when clicked, give this value to the current position.
https://learn.javascript.ru/onscroll

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question