如何使用 Vue Router 处理锚点(书签)? [英] How to handle anchors (bookmarks) with Vue Router?
问题描述
我正在寻找一种使用 Vue Router 处理页内锚点的智能方法.考虑以下几点:
I'm looking for a smart way to handle in-page anchors with Vue Router. Consider the following:
<router-link to="#app">Apply Now</router-link>
<!-- some HTML markup in between... -->
<div id="app">...</div>
文档中描述的滚动到锚点"行为工作很好,除了:
The "scroll to anchor" behavior described in the docs works fine except:
- 当您点击锚点时,它会将您带到
div id="app"
.现在从div
滚动回锚点并再次尝试单击它 -- 这次您将不会跳到div
.事实上,锚将保留类router-link-active
并且 URL 仍将包含哈希/#app
; - 通过上述步骤,如果您刷新页面(URL 仍将包含哈希值)并点击锚点,也不会发生任何事情.
- When you click on the anchor, it brings you down to the
div id="app"
. Now scroll away from thediv
back to the anchor and try clicking it again -- this time you will not jump down to thediv
. In fact, the anchor will retain the classrouter-link-active
and the URL will still contain the hash/#app
; - With the steps above, if you refresh the page (the URL will still contain the hash) and click on the anchor, nothing will happen either.
从用户体验的角度来看,这是非常不幸的,因为潜在客户必须再次手动向下滚动才能到达应用程序部分.
This is very unfortunate from the UX perspective because a potential customer has to manually scroll all the way down again to reach the application section.
我想知道 Vue Router 是否涵盖了这种情况.作为参考,这是我的路由器:
I was wondering if Vue Router covers this situation. For reference, here's my router:
export default new VueRouter({
routes,
mode: 'history',
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return { selector: to.hash }
} else if (savedPosition) {
return savedPosition;
} else {
return { x: 0, y: 0 }
}
}
})
推荐答案
我在资源中找不到任何可以解决您问题的内容,但您可以使用 $route.hash
在您的 >mounted
用于保存
的组件的钩子以解决刷新问题.
I haven't found anything in the resources to solve your issue but you could utitlize the $route.hash
in your mounted
hook of the component that holds your <router-view></router-view>
to solve the refresh issue.
<script>
export default {
name: 'app',
mounted: function()
{
// From testing, without a brief timeout, it won't work.
setTimeout(() => this.scrollFix(this.$route.hash), 1);
},
methods: {
scrollFix: function(hashbang)
{
location.hash = hashbang;
}
}
}
</script>
然后要解决第二次点击的问题,您可以使用 native
修饰符并绑定到您的
.这是一个相当手动的过程,但会起作用.
Then to solve the issue of second clicks you could use the native
modifier and bind to your <router-link></router-link>
. It's a fairly manual process but will work.
<router-link to="#scroll" @click.native="scrollFix('#scroll')">Scroll</router-link>
您可能还可以使用路由器的 afterEach
方法做一些事情,但还没有弄清楚.
There may also be something you could do with the router's afterEach
method but haven't figured that out yet.
这篇关于如何使用 Vue Router 处理锚点(书签)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!