Issue with VueRouter not scrolling to anchor tags was encountered

I am currently tackling an issue with my Vue.js/Laravel8 project on a single page application. I am struggling to make the VueRouter scroll to a specific section on the page. The page is divided into various sections that are accessible by scrolling down, and I want the viewport to automatically scroll to a particular section similar to how the <a> tag functions.

How can I configure the following:

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

to behave like

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

I have made attempts at 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 Illuminate\Support\Facades\Route;


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 the following properties to the clicked anchor:

class="router-link-exact-active"

class="router-link-active"

aria-current="page"

However, the viewport still does not scroll to the desired section. What could be going wrong here?

Answer №1

Consider utilizing the path attribute instead of name and include a hash in the link:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserving the status of your AngularJS application

Can the state of an AngularJS app be preserved using Angular local storage? I am developing an information-based app with a substantial amount of content, and I want to save the user's current "location" so that when they reopen the app later, it open ...

Bidirectional Binding with Directive and Controller

I have a dynamic text field being added to the DOM (from a directive link function) and I want to retrieve the entered value and add it to a scope object in the controller. However, I am always getting undefined as the value. Here is my code snippet: < ...

React component's button has limited functionality when onClick event is triggered

I am facing an issue with creating a collapse menu in my React app. The onClick function for the button only works once. I have tried using a boolean variable to change its state when the button is clicked, but after the first click, the <a> tag beco ...

Preventing Actions in Vue Router When a User Clicks on Menu Links

When dealing with JavaScript Single Page applications, such as Vue.js, and you have a form with a lengthy submit action (like saving something), it is crucial to handle the scenario where the user navigates away before the operation completes. In this case ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

Managing property behavior in Vue 3 using timed functions

Starting my journey as a new vuejs developer, I am eager to dive into Vue and explore its capabilities without relying on any external plugins or components. Currently, I am crafting a basic alert component structured like this: <Alert :show="show ...

Tips for formatting Laravel SQL query clauses on a new line

When working with CodeIgniter, I used to write queries on separate lines using ';' instead of '->'. For example: $color = 'red'; $this->db->select('id, name'); if($color){ $this->db->where('c ...

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

WebVR - lack of orientation and position data from PositionSensorVRDevice

I'm attempting to enable Oculus Rift DK2 orientation input for WebVR, using either Three.js' VRControls (examples/js/controls/VRControls.js) or directly from the PositionSensorVRDevice. However, the values of orientation and position in the Posi ...

I am unable to change the state as the DND kit within the React framework is preventing

element, there seems to be a problem with the deleteProyect function in use. Clicking the button does not remove the object from the array unless clicked rapidly multiple times. This issue could potentially be related to how useEffect is being used. Seekin ...

Is it possible for me to open an object URL in Internet Explorer?

Using Blob and URL.createObjectURL(), I have obtained an "object URL" (blob:) for some binary PDF data. In Chrome and FireFox, when I add an <A/> link HTML element with the programmatically set href attribute as the object URL, clicking on the link ...

Issue with Transparency in Background Loading of FBX Files using Three.js

I am currently exploring three.js and have encountered an issue with transparency not working as expected. Despite trying various settings, I cannot seem to achieve a transparent background - it always defaults to black or interprets the values as an RGB v ...

How can I enable the feature of automatic address population when entering a PIN CODE in an Angular application?

I have created an HTML file where I aim to automatically fill in the DISTRICT, STATE, and CITY fields once a user enters the PIN CODE. The data will be fetched using an API. The API link is: <div class="cardParts5"> <di ...

Trouble with parseJSON when handling form POST in Python

I'm struggling with a javascript HTML page that has an action POST to a python file, expecting a JSON response back. Despite my efforts, I can't figure out how to catch and parse the JSON data. The HTML and python code excerpts below should show ...

Is there a way to confirm if a link is within the same domain before opening it in the current tab?

I am currently working on an Angular 8 application. In this application, there is a specific requirement for handling links. For external links, such as www.ad.nl, clicking on them should open in a new tab. However, if the link belongs to the same domain ...

When utilizing json.loads in Python 2.7, it yields a unicode object rather than a dictionary

I'm currently facing a challenge with converting JSON data into a dictionary, and I'm struggling to find a solution. My situation involves connecting to a Tornado websocket from JavaScript and sending the following data inputted into a textfield ...

The Methods in Vue's optionMergeStrategies do not have access to the 'this' keyword

I have been working on developing a Vue plugin. The plugin includes a custom method called customMethod for each component, which I want to execute after the page has been mounted/created. Although everything seems to be working fine in a basic way, I am f ...

Activate one button out of several in Vue by clicking on it

I am working on a functionality where I have three buttons. When one button is clicked, it should become active while the other two become inactive. However, in my current code, all three buttons are changing together on the click event. Is there a more ...