有没有一种既定的方法可以使用 vue-router (router-link) 链接到特定路由,包括页面上的锚点?
我可以这样做:<router-link to="/page/#section">并且路由器将按预期工作,但前提是我在实际的 /page/ 位置上 - 它会滚动到最近的 id="section" 元素
但是,如果我router-link从其他地方(例如 /page2/)使用相同的路由,则路由器将返回 404,因为它将将该/#section部分视为嵌套路由。
这是指向不同页面上的锚点的路由器链接的解决方案:
使用此链接语法:<router-link to="/page#section">. 在目标页面上,您需要添加自己的滚动逻辑:
mounted() {
var section=this.$router.currentRoute.value.hash.replace("#", "");
if (section)
this.$nextTick(()=> window.document.getElementById(section).scrollIntoView());
},
Run Code Online (Sandbox Code Playgroud)
这很有效,但您可能希望为不存在的锚点添加一些错误处理。
1.安装vue-scrollto:
npm install --save vue-scrollto
Run Code Online (Sandbox Code Playgroud)
2. 设置main.js:
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
Run Code Online (Sandbox Code Playgroud)
3.设置锚ID(最有可能在你的Home.vue):
<template>
<v-content>
<SectionOne id="section-one"/>
<SectionTwo id="section-two"/>
<SectionThree id="section-three"/>
</v-content>
</template>
Run Code Online (Sandbox Code Playgroud)
4. 通过href或链接到锚点router-link:
通过href:
<a href="#" v-scroll-to="'#section-one'">
Scroll to #section-one
</a>
Run Code Online (Sandbox Code Playgroud)
通过router-link:
<router-link to="#" v-scroll-to="'#section-two'">
Scroll to #section-two
</router-link>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8065 次 |
| 最近记录: |