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.
To do this, you need to add the router-view component inside your App. vue file. This component tells Vue Router to mount any component associated with a route where <router-view /> is. Save and exit the main.
You can achieve this by using router-link component of vue-router . You need to pass a prop to in the router-link which will accept a path. Save this answer.
To open a link in a new tab in Vue, create an anchor ( <a> ) element and set its target attribute to _blank , e.g., <a href="https://codingbeautydev.com" target="_blank"></a>. The _blank value specifies that the link should be opened in a new tab.
Suppose we have a /contact route in our vue app, when a user visits the /contact page we need to redirect them to an external url https://www.google.com/contact/ instead of the same domain redirect. To redirect to an external url in Vue, we can use the window. location. href property.
Here is a solution for router links pointing to an anchor on a different page:
Use this link syntax: <router-link to="/page#section">
. On the target page you need add your own scroll logic:
mounted() {
var section=this.$router.currentRoute.value.hash.replace("#", "");
if (section)
this.$nextTick(()=> window.document.getElementById(section).scrollIntoView());
},
This works quite well but you might want to add a bit of error handling for non-existent anchors.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With