VueJS从不同的路线滚动到部分 [英] VueJS scroll to section from different route

查看:25
本文介绍了VueJS从不同的路线滚动到部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Vue 和 Vue Router(具有历史记录模式)滚动到页面上的锚点.

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!

感谢任何帮助!

我的路由器索引:

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: [ ... ]
})

我的导航:

<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>

推荐答案

这是一个老问题,OP 几乎肯定已经找到了解决方案,但是对于遇到此问题的任何人,这应该可以解决问题:

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>

这应该允许您从其他视图/组件访问这些链接,单击时会将您重定向到指定的路由(在本例中为主页),并滚动到指定的哈希值(#enter、#prizes、#faqs).

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).

除了问题中的路由器代码片段外,您还可以使用本机 window.scrollTo 方法添加平滑滚动:

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 }
    }
  }
})

这篇关于VueJS从不同的路线滚动到部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆