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:

https://i.sstatic.net/M58A2.png

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

A JSON object received from an AJAX request is either null or empty

I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

What's the best way in Angular 6 to set focus on an element that's being made content editable?

I am currently utilizing the contentEditable attribute in Angular 6 to allow for editing the content of elements within an ngFor loop. Is there a way to focus on a tag element when its contentEditable attribute is set to true? <div class="tag" *ngFor= ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Exploring Keypress events with Dojo's 'on' module

Recently, I've started utilizing Dojo's latest on module for event handling. It has been working well so far, but a new issue has cropped up. Specifically, when using the keypress event, I am unable to retrieve the character value (such as "2" or ...

What is the process for acquiring a comprehensive catalog of Node.js modules?

Currently, I am working on integrating NPM functionality into my Node.js applications. My goal is to be able to analyze the node modules available on my system. When referring to a "module" in this context, it could either be an identifier like "fd" or a f ...

Issues with excessive firing of JQuery blur and hide functions

I am currently using jQuery v1.11.2 and have set up a basic JSFiddle at this link (http://jsfiddle.net/k1g3upbv/). The layout may not be ideal in JSFiddle due to the integration of Twitter Bootstrap within my project. I quickly put together the JSFiddle, o ...

A guide to creating an HTTPS request using node.js

I am currently in the process of developing a web crawler. Previously, I utilized the following code for HTTP requests: var http=require('http'); var options={ host:'http://www.example.com', path:'/foo/example' }; ...

I was assigned to calculate and transfer the length of the string within the parentheses (written in javascript)

function formatString(str) { const formatted = str.split(',') .map(subStr => `${subStr}(${subStr.length})`) .join(', '); return formatted; } The expected output was "hello(5), world(5), abra(4), carabfa(7), r ...

Troubleshooting Problem with CSS Background-Image in Safari

These questions have been popping up all over the web with little response. I've added some CSS in jQuery like this: $('#object').css('background-image', 'url(../../Content/Images/green-tick.png)'); This works in all b ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

Find the total number of records in fnClick: (datatables.net)

I am struggling with some code where I need to retrieve the total number of records. I posted about it on the datatables.net forum but unfortunately, no one was able to help me... tableTools: { "sSwfPath": window.STATIC_BASE + "scripts/datatable/s ...

Update the JavaScript function following an AJAX request

I have integrated the following jQuery plugin into my project: https://web.archive.org/web/20151007012231/http://www.bulgaria-web-developers.com/projects/javascript/selectbox/ After making an ajax call, I am attempting to refresh it. I have tried using bo ...

The data-ng-bind directive cannot be used with the <option> tag

Currently, I am in the process of learning angular and encountered a problem that has me stuck. Upon researching on AngularJS : Why ng-bind is better than {{}} in angular?, I found out that both {{}} and ng-bind are said to produce the same result. However ...

Is there a way to pass information from Express.js to React without using an API?

My goal is to build a Multi Page APP using both react and express. I find myself uncertain about how to access data sent by express in react without utilizing an API. I am curious if react has the capability to retrieve information stored in HTML props t ...

What is the best way to retrieve an AJAX response in advance of sending it to a template when utilizing DATAT

Recently, I've been working on integrating log tables into my admin panel using the datatable plugin. Despite setting up an ajax call in my datatable, I'm facing issues with retrieving the response before sending it to the table. Here's a s ...

Populate a table with data from a different table using JavaScript

On my webpage, I have a grid of selectable divs that are defined by rows and columns. When I select certain divs, it creates what I'll call "table Copy", a three-dimensional table. If I select different elements, another three-dimensional table calle ...

Merging two separate observableArray into a single entity in knockout js

I am currently working on merging two distinct arrays into a general array and then connecting it using foreach. My View Model: self.cancelledItem1 = ko.computed(function () { return ko.utils.arrayFilter(self.items(), function (item) { ...

Exploring VueJS: How to effectively showcase numerous nested properties within objects

I'm working on a multi-level navigation component in VueJS. While I can successfully retrieve and display the first two levels, I'm struggling to access and display the nested property called name of the children array within my for loop. How can ...

Is there a way to trigger the animation of this text effect only when the mouse is scrolled to that specific section?

Here is a cool typing text effect created using HTML, CSS, and JavaScript. Check out the code below: (function($) { var s, spanizeLetters = { settings: { letters: $('.js-spanize'), }, init: function() { ...