如何使用 Vue Router 创建锚标签

新手上路,请多包涵

我正在创建一个小型 Vue webapp,我想在其中创建一个锚标记。

我已经将 id 给了其中一个 div 我想要这样的锚标记:

 <div id="for-home">
   ....
</div>

这是我的路由器配置:

 export default new Router({
  abstract: true,
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: [
    { path: '/', component: abcView}
  ]
})

但是有了这个锚标签有时有效有时无效,我错过了什么吗?

原文由 Saurabh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 330
2 个回答

我相信你问的是直接跳转到页面的特定区域,方法是导航到页面内的锚标记,如 #section-3

为此,您需要按如下方式修改 scrollBehavior 函数:

 new VueRouter({
    mode: 'history',
    scrollBehavior: function(to, from, savedPosition) {
        if (to.hash) {
            return {selector: to.hash}
            //Or for Vue 3:
            //return {el: to.hash}
        } else {
            return { x: 0, y: 0 }
        }
    },
    routes: [
        {path: '/', component: abcView},
        // your routes
    ]
});

参考: https ://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling

我尝试创建一个 jsFiddle 示例,但由于 mode:'history' 而无法正常工作。如果您复制代码并在本地运行,您将看到它是如何工作的: https ://jsfiddle.net/mani04/gucLhzaL/

通过在 scrollBehavior 中返回 {selector: to.hash} (或 Vue 3 中的 {el: to.hash} ),您将锚标记哈希传递给下一个路由,它将导航到相关部分(使用 id 标记) --- )在那条路线上。

原文由 Mani 发布,翻译遵循 CC BY-SA 4.0 许可协议

对我来说 {selector: to.hash} 解决方案只是拒绝使用 vue-router 4.0.0。以下方法有效并且还启用了平滑滚动。

500 毫秒的超时是为了允许页面加载,因为我发现否则平滑滚动将不会滚动到正确的位置(因为页面仍在加载)。

 const scrollBehavior = (to, from, savedPosition) => {
  if (to.hash) {
    setTimeout(() => {
      const element = document.getElementById(to.hash.replace(/#/, ''))
      if (element && element.scrollIntoView) {
        element.scrollIntoView({block: 'end', behavior: 'smooth'})
      }
    }, 500)

    //NOTE: This doesn't work for Vue 3
    //return {selector: to.hash}

    //This does
    return {el: to.hash};
  }
  else if (savedPosition) {
    return savedPosition
  }
  return {top: 0}
}

原文由 Adam Reis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题