Is there an established way to use vue-router (router-link) to link to a specific route, including an anchor on a page?
I can do this: <router-link to="/page/#section">
and the router will work as expected, but only if I am on the actual /page/ location – it will scroll to the nearest element with id="section"
But if I use the same router-link
from elsewhere (eg. /page2/) the router will return 404, because it will treat the /#section
part as a nested route.
1.
Install vue-scrollto
:
npm install --save vue-scrollto
2.
Setup main.js
:
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
3.
Set anchor ids (most likely in your Home.vue
):
<template>
<v-content>
<SectionOne id="section-one"/>
<SectionTwo id="section-two"/>
<SectionThree id="section-three"/>
</v-content>
</template>
4.
Link to anchor via href
or router-link
:
via href
:
<a href="#" v-scroll-to="'#section-one'">
Scroll to #section-one
</a>
via router-link
:
<router-link to="#" v-scroll-to="'#section-two'">
Scroll to #section-two
</router-link>