My goal is to achieve horizontal scrolling of the viewport by using a button
wrapped in a router-link
that navigates to a vue component
. I was successful in achieving this functionality using anchor tags:
<a href="#about">
<button class="btn">About</button>
</a>
However, when I tried to replace the anchor tags with router-link
, the horizontal scroll stopped working (vertical scroll still works):
<router-link :to="{ hash: 'about' }">
<button class="btn">About</button>
</router-link>
The issue seems to stem from the function defined in router.js
responsible for the scroll behavior:
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 target component, where the viewport is supposed to scroll, is positioned on the right side outside the viewport as follows:
.about {
position: absolute;
transform: translateX(100%);
height: 100vh;
width: 100%;
}
Edit:
Upon changing the button code to:
<button @click="$router.push({ hash: 'about' })">About</button>
The viewport scrolls down approximately 20%
but only vertically, not horizontally. The reason behind this behavior remains unclear. Running
scrollBehavior(to, from, savedPosition) {console.log(to)}
outputs the following information:
{name: 'home', meta: {…}, path: '/', hash: '#about', query: {…}, …}
fullPath: "/#about"
hash: "#about"
matched: [{…}]
meta: {}
name: "home"
params: {}
path: "/"
query: {}
[[Prototype]]: Object