enforcing popstate in vue router

I have a situation where I have links in the middle of a webpage that change the content in a pane below using a nested router setup. My routes related to this issue are structured as follows:

const router = {
  mode: 'history',
  routes: [
    {
      path: '/parent',
      name: 'ParentComponent',
      component: ParentComponent,
      children: [
        {
          path: 'child1',
          name: 'Child1',
          component: Child1,
        },
        {
          path: 'child2',
          name: 'Child2',
          component: Child2,
        },
      ],
    },
  ],
}

The problem I'm facing is that when clicking on a link to navigate to a child path, the content jumps back to the top of the page even if it was previously scrolled down. To address this, I attempted to use scrollBehavior to retain the scroll position like so:

router.scrollBehavior = (to, from, savedPosition) => {
  console.log('savedPosition: ', savedPosition);
  if (savedPosition) {
    return savedPosition;
  }
  return { x: 0, y: 0 };
}

However, I consistently receive a null output for the log. Upon referring to the documentation, it mentions that the savedPosition parameter only holds a value during a popstate navigation event.

Is there a technique to enforce a popstate navigation when clicking on these internal links or is there an alternative method I can utilize to maintain the scroll position upon link click?

Answer №1

Just the other day, I found myself tackling a similar issue

handleScroll (event) {
  if (event.type === 'scroll' && event.deltaY > 0) {
    window.scrollTo(0, document.body.scrollHeight);
  } else {
    window.scrollTo(0, 0);
  }
},

This approach could help you make progress

Answer №2

The information provided in the link to the documentation clarifies everything.

When utilizing the scrollBehavior function, it receives input from the to and from route objects. Additionally, the third argument, savedPosition, is solely accessible during a popstate navigation (initiated by the browser's back/forward buttons).

Given that the page navigation is triggered via links located within the content of the page, this does not constitute a pop state navigation.

Therefore, the recommended approach would be to abstain from utilizing the savedPosition feature of the function, as that specific position will not be retained.

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

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

Error: Appwrite Login Authentication failed due to account.createEmailSession function not recognized as a valid function

Looking for help with Vue and Appwrite? Check out this tutorial: https://appwrite.io/docs/tutorials/vue/step-1 src/appwrite/index.js import { Client, Databases, Account } from "appwrite"; const client = new Client(); client .setEndpoint(" ...

How can I upload a folder with subfolders and keep the structure intact?

I'm working on a form that allows me to upload a folder containing both files and subfolders with more files inside. I managed to upload the folder successfully, but when I check my directory, all the files are in one folder without the subfolders. My ...

Leverage the power of npm packages within a Flutter mobile app's webview

I am currently developing a Flutter mobile app and I am interested in incorporating an npm package that utilizes web3.js and offers additional custom features. My understanding is that Dart code in Flutter is not compiled to JavaScript, so I have been lo ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

Is there a way to connect to multiple values in vue.js when creating a unique multiselect checkbox group?

While I understand how to connect a Vue application to a select element with the multiple attribute, in this scenario, I am dealing with a set of checkboxes that can be toggled on or off. These checkboxes represent features of a residency available for res ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

There seems to be an issue with the server: Xt1.deprecate function is not defined

Currently, I am utilizing next.js version 13.4.12 with next-auth version 4.22.3 and prisma version 5.0.0, while also incorporating @next-auth/prisma-adapter version 1.0.7 in a TypeScript setup. Additionally, I have diligently followed all the necessary bo ...

Minimize the visibility of the variable on a larger scale

I have a nodejs app where I define global variables shared across multiple files. For example: //common.js async = requires("async"); isAuthenticated = function() { //... return false; }; //run.js require("common.js"); async.series([function () { i ...

Retrieving images from GridFs and displaying them in an Angular application

I have been working on storing images from my angular app in MongoDB using GridFs. However, I am having trouble retrieving the images from the database to the app. I am using a custom objectId for the query. UPDATE After some changes, I managed to get t ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

Locate the closest pals near my present whereabouts

Is it possible to find my friends by obtaining their location from their mobile phones when they are near me? I have a code snippet below with the variable cities where I can input the numbers of my friends. Can I achieve this or do I need to make some m ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

What is the most strategic way to conceal this overlay element?

Currently, the website I'm developing features a series of navigation elements at the top such as "Products" and "Company." Upon hovering over the Products link, an overlay displays a list of products with clickable links. Positioned at the top of the ...

ESLint does not recognize the components used in Element UI

I've been working with Vue.js and Element UI components. However, when I try to use elements like Input or Col, ESLint throws an error with the message invalid-end-tag. I have already added eslint-plugin-vue to my setup, so why isn't ESLint reco ...

Adjust the height of Revolution Slider on mobile devices using initialization

To see an example of the Revolution Slider, please check out the top hero section on this page. If you are looking for the initialization code, you can find it in this javascript file: function dz_rev_slider_5(){ if(dzQuery("#rev_slider_11_1" ...

Error message from BitBucket pipeline indicates that the npm command was not found

Upon deploying code to my server via the Bit Bucket scp pipeline, I encountered an issue with another pipeline meant to install node modules and start the node server. The pipeline returned a failed status and displayed the following error: ./server-run.s ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

The external function in HTML Form's onsubmit attribute is failing to execute

My HTML Form has an onsubmit event that should call a validate() function. Everything works fine when the validate() function is inside a script tag at the end of the body tag. But if the validate() function is in an external JavaScript file, like in thi ...