VueJS scroll to section from different route

孤者浪人 提交于 2021-02-19 03:55:13

问题


I am trying to scroll to an anchor on a page using Vue and Vue Router (with history mode).

When on the index page, the scroll behaviour works as expected by jumping to the section.

However, when I am another page, it loads the index page at the top and not where the anchor is pointing to.

I’m sure it’s a very simple thing but can’t get my head round it!

Any help is appreciated!

My router index:

export default new Router({
  scrollBehavior: function(to, from, savedPosition) {
    if (to.hash) {
      return {selector: to.hash}
    } else {
      return {x: 0, y: 0}
    }
  },

  mode: 'history',
  routes: [ ... ]
})

My Navigation:

<router-link @click.native="closeNav" to="/#enter">Enter</router-link>
<router-link @click.native="closeNav" to="/#prizes">Prizes</router-link>
<router-link @click.native="closeNav" to="/#faqs">FAQ</router-link>
<router-link @click.native="closeNav" to="/contactus">Contact</router-link>

回答1:


This is a bit of an old question and OP has almost surely found a solution already, but for anyone running into this problem, this should do the trick:

<router-link :to="{ name: 'Homepage', hash: '#enter' }">Enter</router-link>
<router-link :to="{ name: 'Homepage', hash: '#prizes' }">Prizes</router-link>
<router-link :to="{ name: 'Homepage', hash: '#faqs' }">FAQ</router-link>
<router-link :to="{ name: 'Contact' }">Contact</router-link>

This should allow you to have these links accessible from other views/components, and when clicked will redirect you to the named route (Homepage in this case), and scroll to the hash specified (#enter, #prizes, #faqs).

In addition to the router code snippet in the question, you can add smooth scrolling using the native window.scrollTo method:

export default new Router({
  routes: [],
  mode: 'history',
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return window.scrollTo({ 
        top: document.querySelector(to.hash).offsetTop, 
        behavior: 'smooth' 
      })
    } else {
      return { x: 0, y: 0 }
    }
  }
})



回答2:


I am using scrollIntoView() instead of window.scrollTo()

export default new Router({
  routes: [],
  mode: 'history',
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return document.querySelector(to.hash).scrollIntoView({ behavior: 'smooth' });
    } else {
      return savedPosition || { x: 0, y: 0 }
    }
  }
})


来源:https://stackoverflow.com/questions/51379731/vuejs-scroll-to-section-from-different-route

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