VueRouter not scrolling to anchor tags

I am working on a Vue.js/Laravel8 project on a single page app and can’t get VueRouter to get to scroll to the section I want. The page consists of different sections which are reachable if user scrolls down and I want the viewport to scroll to a section similar to how the <a> tag works.

How do I make

<router-link :to="{ name: section1 }">Section1</router-link>

behave like

<a href="#section1">Section1</a>?

I’ve tried the following:

app.js:

require('./bootstrap')

import Vue from "vue"
import App from "../vue/app"
import router from "./router";

const app = new Vue({
    el: "#app",
    components: { App },
    router
});

router.js:
import Vue from "vue";
import VueRouter from "vue-router";

import Home from "../vue/home";
import Section1 from "../vue/section1";

Vue.use(VueRouter);

export default new VueRouter ({
    mode: "history",
    base: process.env.BASE_URL,
    routes: [
        {path: "/", name: "home"},
        {path: "/section1", name: "section1", component: Section1},
    ],
    scrollBehavior(to, from,  savedPosition) {
        console.log(savedPosition)
        if (savedPosition) {
            return savedPosition;
        } else if (to.hash) {
            return {
                selector: to.hash
            }
        }
    }
});

web.php:
<?php

use IlluminateSupportFacadesRoute;


Route::get('/{any}', function () {
    return view('welcome');
})->where('any', '.*');

app.vue:
<template>
  <div class="container">
    <main>
      <home></home>
      <section1></section1>
    </main>
    <router-view></router-view>
  </div>
</template>

navigation.vue:
<template>
  <div class="navbar">
    <router-link :to="{ name: 'section1' }">Section1</router-link>
  </div>
</template>

section1.vue:
<template>
  <section id="section1" class="section1">
    <div class="image"></div>
  </section>
</template>

<router-link> tags are correctly converted into <a> tags in the browser and VueRouter applies following properties to the clicked anchor:

class="router-link-exact-active"

class="router-link-active"

aria-current="page"

But the viewport is not scrolling to the desired section still. What am I doing wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try to use path insted of name and add hash to link:

<router-link :to="{ path: '/section1', hash: '#section1' }">Section1</router-link>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x