The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this:

import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";


const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    {
        path: "/Portfolio",
        name: "Portfolio",
        component: () =>
            import(/*webpackChunkName: "DestinationDetails" */ "../views/Portfolio"),
    },
    {
        path: "/Services",
        name: "Services",
        component: () =>
            import(/*webpackChunkName: "DestinationDetails" */ "../views/Services"),
    },

    {
        path: "/details/:id",
        name: "PortfolioDetails",
        component: () =>
            import(
                /*webpackChunkName: "DestinationDetails" */ "../views/PortfolioDetails"
            ),
    },
    {
        path: "/:pathMatch(.*)*",
        redirect: "/Home",
    },
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});

export default router;

In addition, I am fetching paths from an API "https://api.fake.rest/ca2a6662-22d0-4010-ba08-0440ffe813ab/menu" using a v-for loop. Out of the 5 URL paths retrieved, 3 have a value of "#" and the remaining 2 have normal paths.

<div
                    v-for="(men, index) in webMenu.menu_items"
                    :key="index"  class=" mt-32"
                >
                    <router-link class="w-full" :to="men.url"> {{men.name}} </router-link>
                    
                </div>

                <p class="font-bold">{{webMenu.menu_text}}</p>
            </div>

However, I am encountering an issue where upon initial webpage load everything works as expected, but after clicking on the portfolio or services link, the paths to other pages get modified.

For instance, if I navigate to the portfolio page and then attempt to go back to the home page, the route path changes to "portfolio#" causing difficulty in switching pages.

I am seeking help in understanding why this happens and any possible solutions to resolve it. Any insights are greatly appreciated.

Answer №1

I encountered a similar issue myself.

The problem for me arose when I tried to redirect to a new page using router.push() upon clicking a div element.

Despite using

@click.stop = "myFunction"
, a '#' symbol was being added to the URL instead of redirecting the user.

I experimented with different approaches, including utilizing the event object and trying event.stopPropagation(), but the outcome remained the same.

Ultimately, switching to @click.prevent fixed the issue and everything functioned as intended.

PS:

To troubleshoot errors, you can also utilize a catch block like so:

this.$router..push({
        name: "PAthName",
        params: { id },
        query: { id }
      })
      .catch(e => {
        console.log("Errors", e);
      });

Answer №2

Finally got around to making the necessary update.

The solution turned out to be quite simple, I just needed to modify the binding in this section from

<router-link class="w-full" :to="men.url"> {{men.name}} </router-link>

to

<router-link class="w-full" :to="`/${men.url}`"> {{men.name}} </router-link>

and just like that, problem solved!

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

Mastering the management of various events within React Material UI components

I am working with a Material UI Switch Component and need to detect click events on it. In certain situations, I want to prevent the change event from triggering. What is the most effective way to achieve this? While I have previously used event.preventD ...

Customize the color of the label and underline in a Reactjs material-ui TextField when the field input

https://i.stack.imgur.com/oJ2ah.png <TextField id="standard-full-width" label="Password" style={{ margin: 8 }} fullWidth margin="normal" placeholder="*******" /> Struggling to understand how to modify the color of the label ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Using a temporary variable within a Vue loop

Currently, I am utilizing Vue along with Vuetify to create a menu containing links using the treeview component. The data source I'm working with is a nested JSON structure. The issue I am facing is regarding linking the parent "to" with its children ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Combining Bootstrap Vue: utilizing class names alongside HTML tags

(Bootstrap-Vue 2.0, Vue.js 2.5) Is it possible to combine traditional CSS Bootstrap 4 classes with Bootstrap-Vue? For example, can I use the following code snippet: <section id="introduction"> <b-container class="h-100"> & ...

What is the best way to retrieve my data/json from req.body in Express?

Recently, I started working with node.js and encountered an issue while trying to access JSON data on my node.js server through a post request. The goal is to send this data to an API and then pass it back to my front-end JavaScript file. Despite being abl ...

Customize Vue or Nuxt by including a highly detailed tag in the <head> section

Trying to generate static page templates using Vue/Nuxt but struggling to find a way to insert a very specific tag into the head section of each generated page. It's not a meta, script, style, or link tag, and it appears that the options in nuxt.confi ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

Scrolling to a specific anchor in a React webpage when the URL is opened in

Imagine having a component "Post" that contains multiple components "Comment". How can we make the application automatically scroll down to a specific comment when entering a URL like this: /post/:postId/#commentId The route for postId /post/:postId is a ...

Error message: JavaScript JSON variable undefined in AWS Lambda

My lambda function is being triggered by an IoT rule that sends a MQTT message in JSON format. I am facing an issue where the top level fields are logging correctly, but when it comes to nested objects in the JSON, they appear as "undefined". Even after tr ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Is it possible to showcase two modals on a single page, positioning one to the left and the other to the right using Bootstrap?

Can someone help me learn how to display two modals on the same screen, one on the left and one on the right? I am new to bootstrap and would appreciate some guidance! ...

Angular: The issue with lazy-loading a decorator and how to solve it

How to Register a Decorator Synchronously angular .module('myApp') .decorator('$controller', MyDecorator); angular .module('myApp') .controller('MyCtrl', MyCtrl); Registering a Decorator Asynchronously $t ...

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

Exploring the Factory Design Pattern Together with Dependency Injection in Angular

I'm currently implementing the factory design pattern in Angular, but I feel like I might be missing something or perhaps there's a more efficient approach. My current setup involves a factory that returns a specific car class based on user input ...

Utilizing Regex Patterns to Manipulate CSS Attributes

I am dealing with a string containing CSS properties and their values: str = "filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); background: -webkit-linear-gradient(top, black, wh ...

Exploring the capabilities of Socket.IO in Node.js for establishing a connection with an external server

Background: My localhost (referred to as Server A) hosts a node.js server, while an external server running node.js can be found at (known as Server B). Although I lack control or access over Server B, which serves as a dashboard site for an IoT device in ...