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

A guide on automating the html5 color picker using input type="color" in selenium webdriver

When interacting with an HTML color input element, a color picker window pops up that prevents viewing the DOM. I am looking for a solution to either select a color and close the window or enter a hex code in the popup's text box. Can anyone provide m ...

What is the correct way to establish and terminate a MongoDB connection in a Node.js application?

Hey everyone, I have a piece of code at this link (https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js) and I'm curious if I am properly starting and ending my database connection. Should I connect and end the db connection in every a ...

The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue? Below is my updated code: // Define the canvas / graph dimensions var margin = {top: ...

Utilize jQuery to substitute numbers with strings through replacement

My question pertains to the topic discussed here. I am looking for a more refined jQuery replacement function that can substitute a number with a string. My PHP script returns numbers in the format of 1.27 Based on a specified range, these numbers need ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

What steps do I need to take to adjust this function based on the timezone?

Is there a way to retrieve the current time based on a specific timezone of my choice? let getCurrentTime = () => { var today = new Date(); var hh = String(today.getHours()) var mm = String(today.getMinutes()) //January is 0! var ss = ...

"The function within the Sails.js model is not properly returning a value when rendered

Within my Sails.js application, I am currently attempting to retrieve the total number of users that have been approved in my database and utilize this count variable within my view by employing the count() query. Below is the snippet of code present in my ...

Customizing the "added to cart" message in Woocommerce and setting up a notification system for customers

My main focus is on customizing the Woocommerce notation system for a personalized shopping cart experience. After some research, I stumbled upon a very helpful user response which suggested modifying the message by adding the following code snippet to th ...

Seeking a solution for inserting input values into a JSON file within a node.js environment

As I was developing my new project, a to-do list web application, Below is the code snippet from 'todo.html' : <html> <head> <title>My TODO List</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...

In the realm of Node.js and Express, an error has been thrown: "Router.use() cannot function without a middleware component, yet received a + gettype(fn)."

While developing an application with Node.js, I encountered the following error: throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^ TypeError: Router.use() requires a middleware function but got a ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

Error message: A state has not been defined within the onload function

I'm facing an issue where I am attempting to assign a data URL of an image to a state in Vue.js, but it is not getting assigned properly. After converting a blob URL to a data URL, the state does not contain the correct data URL. While the imgSrc doe ...

Error encountered while attempting to install ungit on Windows XP: Unable to locate file directory in C:/Documents

Ungit seems like the ideal tool to gain a better understanding of git, thanks to its graphical interface that simplifies the process. I came across this video explanation which is very helpful in grasping how git functions, even if you don't intend to ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...