I want to use a button wrapped into router-link to scroll the viewport horizontally (100% to the right to a vue component. This works fine with anchor tags:
<a href="#about">
<button class="btn">About</button>
</a>
but as soon as I try to replace them with router-link the horizontal scroll stops working (vertical scroll still works):
<router-link :to="{ hash: 'about' }">
<button class="btn">About</button>
</router-link>
This function inside router.js is responsible for the scroll:
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
export default new VueRouter({
mode: "history",
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return window.scrollTo({top: document.querySelector(to.hash).offsetTop, behavior: 'smooth'});
}
return window.scrollTo({top: 0, behavior: 'smooth'});
}
});
The component to which the viewport is to be scrolled has been placed on the right side outside the viewport like so:
.about {
position: absolute;
transform: translateX(100%);
height: 100vh;
width: 100%;
}
Edit:
Changing the button to:
<button @click="$router.push({ hash: 'about' })">About</button>
makes the viewport scroll down about 20% and only vertical , not horizontal. I don't know why this behaviour occurs. scrollBehavior(to, from, savedPosition) {console.log(to)} shows this:
{name: 'home', meta: {…}, path: '/', hash: '#about', query: {…}, …}
fullPath: "/#about"
hash: "#about"
matched: [{…}]
meta: {}
name: "home"
params: {}
path: "/"
query: {}
[[Prototype]]: Object
Try with:
<button @click="$router.push({ hash: 'about' })">About</button>