I’m working on a Vue 3 project and encountering an issue where the Vue Router is not reflecting the correct routes. When I navigate to any route, 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;
And this is how I’m 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");
});
Somehow when I go /admin it does not reflect and stays at 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>
When I try to navigate to any route like /admin or /cars, the URL does not change and the application remains on the home page. The console output shows the following route information when I attempt to navigate:
2
Answers
The issue is related to the use of createMemoryHistory instead of createWebHistory. createMemoryHistory is typically used for server-side rendering or testing, while createWebHistory is used for client-side navigation in a typical web application.
I think "Router view for admin pages" have to be inside "Router view for website pages".
So the code will be