Vue Router Issue: Unable to Navigate to Different Routes, Always Redirected to Home Page

I am currently working on a Vue 3 project and am facing an issue with the Vue Router not displaying the correct routes. Whenever I try to navigate to routes such as /cars or /admin, the URL does not update and the application stays on the home page.

import { createMemoryHistory, createRouter } from "vue-router";

import HomePage from "../views/website/index.vue";
import CarsPage from "../views/website/CarsPage.vue";
import AdminLayout from "../components/admin/AdminLayout.vue";
import AdminDashboard from "../views/admin/index.vue"; // Assuming AdminDashboard is exported as default

const routes = [
  {
    path: "/",
    name: "home",
    component: HomePage,
  },
  {
    path: "/cars",
    name: "cars",
    component: CarsPage,
  },
  {
    path: "/admin", // Make sure to add '/admin' as a separate route
    component: AdminLayout,
    children: [
      {
        path: "", // Making '/admin' itself redirect to '/admin/dashboard'
        redirect: "dashboard",
      },
      {
        path: "dashboard",
        name: "admin-dashboard",
        component: AdminDashboard,
        meta: { requiresAuth: true },
      },
      // Add more admin routes here if needed
    ],
  },
];

const router = createRouter({
  history: createMemoryHistory(),
  routes,
});

export default router;

This is how I am loading it in main.js:

import { createApp } from "vue";
import App from "./App.vue";
import Antd from "ant-design-vue";

import router from "./router/router";
const app = createApp(App);
app.use(Antd);

app.use(router);
router.isReady().then(() => {
  console.log("helllo");
  app.mount("#app");
});

When I try to navigate to /admin, it does not reflect and remains on the HomePage

<template>
  <div id="app">
    <!-- Header for website pages -->
    <header>
      <!-- Include website-specific header content here -->
    </header>

    <!-- Router view for website pages -->
    <router-view />
    <!-- {{ $route }} -->

    <!-- Footer for website pages -->
    <footer>
      <!-- Include website-specific footer content here -->
    </footer>

    <!-- Router view for admin pages -->
    <router-view name="admin" />
  </div>
</template>

<script>
import Footer from "./components/Footer.vue";
import Header from "./components/Header.vue";
export default {
  name: "App",
  components: { Header, Footer },
  created() {
    this.$router.push("/admin/dashboard");
  },
};
</script>

Whenever I attempt to navigate to routes like /admin or /cars, the URL does not change and the application stays on the home page. The console output displays the route information as follows:

Answer №1

The problem stems from opting for createMemoryHistory over createWebHistory. createMemoryHistory is usually reserved for server-side rendering or testing purposes, whereas createWebHistory is the go-to for client-side navigation in a standard web application.

Answer №2

In my opinion, the "Admin pages router view" should be nested within the "Website pages router view". Here is how the code could look:

<template>
    <div id="app">
        <!-- Header for website pages -->
        <header>
        <!-- Insert website-specific header content here -->
        </header>

        <!-- Router view for website pages -->
        <router-view>
            <!-- Router view for admin pages -->
            <router-view name="admin" />
        <router-view />
        <!-- {{ $route }} -->

        <!-- Footer for website pages -->
        <footer>
            <!-- Insert website-specific footer content here -->
        </footer>
    </div>
</template>

<script>
import Footer from "./components/Footer.vue";
import Header from "./components/Header.vue";
export default {
    name: "App",
    components: { Header, Footer },
    created() {
        this.$router.push("/admin/dashboard");
    },
};
</script>

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

Tips for triggering a sound only when transitioning from a true to false value for the first time

I have data for individuals that includes a dynamically changing boolean value. This value can be true or false, and it updates automatically. The webpage fetches the data every 5 seconds and displays it. If the value for any person is false, a sound is p ...

"Unlocking the potential of vselect in Vue.js: mastering the art of rendering elements in a

I have a Vue.js form with select drop-downs, and I am attempting to utilize the library to achieve this. According to the documentation, I need to pass an array into it, and I'm using an axios method to fetch the options for the drop-downs. The data ...

Can Vue.js be affected by cascading updates?

Presentations by Tom Occhino and other React speakers have discussed how Angular's 2-way bindings can lead to cascading updates, making it challenging to understand. These issues with Angular are unfamiliar to me since I haven't worked with it be ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

Abstraction of middleware functions

After reviewing my middleware Express functions, I realized that there is repeated code. The first function is as follows: const isAdmin = async (req, res, next) => { try { const requestingUser = await knex('users') ...

Preserve object properties while allowing for changes to be made without affecting

I am in need of transferring specific properties from one object to another while ensuring that the original object remains mutable. Here is the original object: var sourceObject = { "key1": "value1", "key2": "value2 ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

Uploading multiple strings to an Amazon S3 bucket using Node.js by piping a string

Suppose I have a simple loop similar to the one shown below: for (const i=0; i<3; i++) { to(`This incrementer is ${i}`) } At the end of the loop, I expect my file to contain: This counter is 0 This counter is 1 This counter is 2 I at ...

Deactivating upcoming weeks according to the year in Angular 8

In the user interface, there are dropdowns for selecting a year and a week. Once a year is selected, the list of weeks for that year is displayed in the week dropdown. Now, the requirement is to disable the selection of future weeks. For example, for the ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Using React.js to dynamically display or hide elements generated within a component

I'm currently working on a project where I need to dynamically generate form fields based on certain criteria. Specifically, I want to hide some fields and only show them when other specific conditions are met, a common requirement in form designs. Fo ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

Issue with passing parameter in Jquery AJAX request to controller function

Currently, I am integrating a Jquery AJAX Call into my MVC Application. Here is an overview of how my view is structured: <p> Name @Html.TextBox("Name") Date @Html.TextBox("Date") <input type="submit" id="SubmitName" value="Submit" /& ...

The Vuex function being mapped is not recognized as a function, yet it still manages to load correctly

Whenever I try to execute a mapped Vuex action inside the mounted hook, the action successfully runs but I encounter a "TypeError: xxx is not a function" message in the console. Below is the complete script section for this particular component: <sc ...

Tips for toggling the visibility of an element when a button is clicked in React

In my todo list, I need to display the details of each item when clicked on a button. There are two buttons available: "View Details" and "Hide Details". Below is the code snippet: class Todos extends React.Component{ construc ...

Can you create a stroke that is consistently the same width as the container BoxElement?

Utilizing a BoxElement provided by the blessed library, I am showcasing chat history. New sentences are inserted using pushLine. To enhance readability, days are separated by lines (which are added using pushLine). The width of each line matches that of t ...

Pug template syntax for importing JavaScript files with links

My Programming Dilemma In my NodeJS webserver setup, I use Express and Pug to serve HTML and JavaScript files. Here's a snippet of how it looks: index.pug html head title Hello body h1 Hello World! script(src='s ...

Issues with the @input listener failing to work on a customized component

I'm currently experimenting with a unique component from the PrimeVue library. It claims to support any event: "Any valid event such as focus, blur and input are passed to the underlying input element." The event listener seems to be workin ...