Modifying routes within the beforeEach function causes issues when the callback incorrectly passes in erroneous routes to and from

I'm currently in the process of developing a mobile frontend using Vue. My goal is to have route transitions dynamically change to slide either left or right based on the current tab index.

To accomplish this, I've set up a transition component in my App.js that switches the transition depending on the route like so:

<transition :name="$route.meta.transition" mode="out-in">

My approach involves setting up a beforeEach hook on each route change to modify both the current route's meta.transition and the target route's .meta.transition.

Below are the route definitions:

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/routines',
      name: 'routines',
      component: () => import('../views/Routines/IndexView.vue'),
      meta: { transition: 'slide-right', index: 0 }
    },
    ...
  ]
})

Here is the hook I'm implementing to replace the to and from routes with modified routes containing the appropriate transition string:

router.beforeEach((to, from, next) => {
  console.log(to, from)
  if (to.meta.index < from.meta.index) {
    console.log({...to, meta: {...to.meta, transition: 'slide-left'}})
    router.addRoute({...to, meta: {...to.meta, transition: 'slide-left'}})
    console.log({...from, meta: {...from.meta, transition: 'slide-left'}})
    router.addRoute({...from, meta: {...from.meta, transition: 'slide-left'}})
  }
  next()
})

However, I encountered an issue where the to and from parameters do not contain the component keys I previously defined. This resulted in an error when replacing routes using addRoute and then navigating back: Error: Invalid route component

I confirmed that the to and from objects are indeed invalid routes:

How can I resolve this problem to achieve the desired dynamic sliding behavior? I believe the hook strategy I adopted makes sense. In the future, I plan to implement additional logic to enable child pages to zoom in and out when transitioning between parent and child pages.

Thank you!

Answer №1

Instead of using the router.addRoute() method, consider updating the route meta directly within a router hook. According to the guidelines in the Vue Router documentation, it is recommended to utilize the afterEach() hook:

// router.js
router.afterEach((to, from) => {
  to.meta.transition = to.meta.index < from.meta.index ? 'slide-right' : 'slide-left'
})

Check out the demo here

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

Why is my react-hook-form sending an array with no data when making an axios request?

Within a container, I have mui Chips that contain labels. The objective is to utilize these chips as selectors, using onClick to add the label values to a list that will be sent in an Axios request. This needs to be achieved without the use of a textfield, ...

Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt. My approach involves using JavaScript and vue.js. Function responsible fo ...

Launching ExpressJS and ReactJS on Heroku

Currently working on a project that combines express and react. When attempting to deploy it to Heroku via git push, I encountered an error upon checking the heroku logs. The specified webpage then shows a message indicating that it cannot locate a build ...

Does Node.js support backward compatibility?

There is a common belief that Node.js is backwards compatible, meaning scripts running in Node.js N should also work in Node.js N+1. I have been unable to find any documentation confirming this assumption. Is there another way to verify compatibility aside ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

Learn how to effectively declare data as global within Angular2 or Typescript

I am facing an issue with fetching the id inside the Apiservice despite being able to get it in the console. Can anyone provide assistance on how to solve this problem? TS: deleteProduct(index,product) { var token = this.auth.getAccessTokenId(); ...

Displaying 'Undefined' instead of 'Cleared messages count' in the Clear Command

My goal is to display the number of deleted messages on an embed, but when the embed is sent, it shows bot deleted undefined messages. Here's a screenshot: I want it to show bot deleted ex: 15 messages. It works fine as a regular message but not on a ...

Tips for designing a personalized payment page in PayPal for flexible one-time and subscription-based payments

How can I display a PayPal checkout page with custom fields such as tax and total amount when a user makes a payment for a custom amount? Can multiple fields like sales tax and total amount be added? In addition to that, our web application already has Pa ...

How can I properly customize and expand upon a Material UI ListItem component?

I'm currently working with TypeScript version 3.4.5 and Material UI version 4.2. I have the following code snippet: interface MyItemProps { name: string; value: string; } function Item({ name, value, ...props }: ListItemProps<'li&apo ...

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

Exploring the File Selection Dialog in Node.js with TypeScript

Is it possible to display a file dialog in a Node.js TypeScript project without involving a browser or HTML? In my setup, I run the project through CMD and would like to show a box similar to this image: https://i.stack.imgur.com/nJt3h.png Any suggestio ...

Form submission is failing due to a single checkbox not being submitted and an error is occurring with MultiValueDictKeyError during

<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group" ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

What is the equivalent of $.fn in AngularJS when using angular.element()?

Currently, I am conducting a directive unit test using jasmine. The test is now functional, but I need to find an alternative for $.fn in angularjs since the use of $ is prohibited in my workplace. Code: (function scrollTopEventDirective(application) ...

Redirecting to new page after submitting form using Ajax

I'm having some trouble with my HTML form submission using JQuery and AJAX. After successfully submitting the form, I want to display a modal and then redirect to another page based on certain conditions. I've written the logic in my JS file wh ...

Is it possible to integrate Google Analytics with Next.js version 13?

Is there anyone who has successfully integrated Google Analytics with NextJS 13? I tried following the steps outlined in this thread: How to implement Google Analytics with NextJS 13?, but despite doing everything as instructed, I am not seeing any data o ...

Tips for preventing the overwriting of a JSON object in a React application

I'm trying to compare two JSON objects and identify the differing values in the second JSON object based on a specific key. My goal is to store these mismatched values in a new JSON object. The current issue I'm facing is that when there are mult ...

Vue: monitoring the 'value' of a v-model within a component

I have a component with a v-model directive that looks like this: <my-component v-model="someData.someProp"></my-component> My goal is to watch this specific piece of data within the component and make adjustments based on any change ...

Utilizing Parent Scope Variables in AngularJS Directives with Isolated Scopes

I'm feeling a bit lost here (edit: after clarification, my question is "Why isn't the directive recognizing the attributes passed to it?"), even though I thought I had a good grasp on it. I'm having trouble accessing the properties of the pa ...