Vue路由器:将链接锚定到页面中的特定位置,例如/route/#anchor



是否有一种既定的方法可以使用vue路由器(路由器链接(链接到特定的路由,包括页面上的锚?

我可以这样做:<router-link to="/page/#section">和路由器将按预期工作,但只有当我在实际的/页面/位置时,它才会滚动到最近的元素,id="section">

但是,如果我使用来自其他地方的相同router-link(例如/page2/(,路由器将返回404,因为它将把/#section部分视为嵌套路由。

1。安装vue-scrollto:

npm install --save vue-scrollto

2。设置main.js:

import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)

3。设置锚点ID(很可能在Home.vue中(:

<template>
<v-content>
<SectionOne id="section-one"/>
<SectionTwo id="section-two"/>
<SectionThree id="section-three"/>
</v-content>
</template>

4。通过hrefrouter-link:链接到锚点

通过href:

<a href="#" v-scroll-to="'#section-one'">
Scroll to #section-one
</a>

通过router-link:

<router-link to="#" v-scroll-to="'#section-two'">
Scroll to #section-two
</router-link>

以下是指向不同页面上锚点的路由器链接的解决方案:

使用以下链接语法:<router-link to="/page#section">。在目标页面上,您需要添加自己的滚动逻辑:

mounted() {
var section=this.$router.currentRoute.value.hash.replace("#", "");
if (section)
this.$nextTick(()=> window.document.getElementById(section).scrollIntoView());
},

这工作得很好,但您可能需要为不存在的锚点添加一些错误处理。

vue-router文档中有一个示例,它们模拟"滚动到锚点"行为:https://router.vuejs.org/guide/advanced/scroll-behavior.html

他们链接到页面底部附近的示例:https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js

我自己还没有尝试过,但似乎对他们有效。

最新更新