I am working on a vue 2 app using vue 3 router. I want to have a route like /user and within that /user/profile and /user/settings. So, I configured my vue router.js file as
router.js
import Vue from "vue";
import Router from "vue-router";
import User from "../components/User";
import Settings from "../components/Settings";
import Profile from "../components/Profile";
Vue.use(Router);
export default new Router({
mode: "history",
routes: [
{
path: "/user",
name: "user",
component: User,
children: [
{
path: "/settings",
name: "settings",
component: Settings
},
{
path: "/profile",
name: "profile",
component: Profile
}
]
}
]
});
User.vue
<template>
<h1>User</h1>
</template>
Settings.vue
<template>
<h1>Settings</h1>
</template>
Profile.vue
<template>
<h1>Settings</h1>
</template>
App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "app",
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Whenever I am visiting /user
, the User.vue is rendered but when I am trying to visit /user/profile
or /user/settings
, nothing is rendered in the DOM. I followed Child route component not rendering in vue js and Activate router-link that has multi level nested routes with CRUD setup but no luck. What I want is User.vue should be rendered on /user
route and only the contents of Profile.vue
should be rendered when we are in /user/profile
route. I tried to include <router-view />
in User.vue
but I am getting both User.vue
and Profile.vue
contents in /user/profile
. I am attaching codesandbox link to see it in live and to get a better understanding as I am not sure how to set it up in SO.
Link: https://codesandbox.io/s/nostalgic-sky-3wvhqr?file=/App.vue:0-354
How can I achieve this?
CodePudding user response:
UserParent.vue
<template>
<router-view />
</template>
router.js
routes: [
{
path: "/user",
component: UserParent,
children: [
{
path: "/",
name: "user",
component: User
},
{
path: "/settings",
name: "settings",
component: Settings
},
{
path: "/profile",
name: "profile",
component: Profile
}
]
}
]
CodePudding user response:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Router({
routes: [
{
{
path: "/",
redirect: "/user",
component: () => import("@/view/layout/user"),
children: [
{
path: "/settings",
name: "settings",
component: () => import("@/view/pages/settings.vue")
},
{
path: "/profile",
name: "profile",
component: () => import("@/view/pages/profile.vue")
}
]
}