Vue 路由器:将链接锚定到页面中的特定位置,例如/路线/#anchor
Vue router: anchor links to a specific place in a page e.g. /route/#anchor
有没有既定的方法使用vue-router(router-link)来link到一个特定的路由,包括一个锚点页数?
我可以这样做:<router-link to="/page/#section">
路由器将按预期工作,但前提是我在实际的 /page/ 位置上——它会滚动到最近的 id=[=21= 元素]
但是如果我从其他地方使用相同的 router-link
(例如 /page2/),路由器将 return 404,因为它会将 /#section
部分视为嵌套路由.
vue-router 文档中有一个模拟 "scroll to anchor" 行为的示例:https://router.vuejs.org/guide/advanced/scroll-behavior.html
他们 link 靠近页面底部的示例:
https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js
我自己还没有尝试过,但似乎对他们有用。
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。
Link 通过 href
或 router-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>
这是路由器 links 指向不同页面上的锚点的解决方案:
使用此 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(router-link)来link到一个特定的路由,包括一个锚点页数?
我可以这样做:<router-link to="/page/#section">
路由器将按预期工作,但前提是我在实际的 /page/ 位置上——它会滚动到最近的 id=[=21= 元素]
但是如果我从其他地方使用相同的 router-link
(例如 /page2/),路由器将 return 404,因为它会将 /#section
部分视为嵌套路由.
vue-router 文档中有一个模拟 "scroll to anchor" 行为的示例:https://router.vuejs.org/guide/advanced/scroll-behavior.html
他们 link 靠近页面底部的示例: https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js
我自己还没有尝试过,但似乎对他们有用。
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。
Link 通过 href
或 router-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>
这是路由器 links 指向不同页面上的锚点的解决方案:
使用此 link 语法:<router-link to="/page#section">
。在目标页面上,您需要添加自己的滚动逻辑:
mounted() {
var section=this.$router.currentRoute.value.hash.replace("#", "");
if (section)
this.$nextTick(()=> window.document.getElementById(section).scrollIntoView());
},
这很好用,但您可能想为不存在的锚点添加一些错误处理。