如何正确配置 vue 3 路由器子项以使嵌套路由按预期工作?
How to configure vue 3 router children properly to have nested routes working as expected?
我正在使用 vue 3 路由器开发一个 vue 2 应用程序。我想要一条像 /user 这样的路线,并且在 /user/profile 和 /user/settings 之内。所以,我将我的 vue router.js 文件配置为
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>
每当我访问 /user
时,都会呈现 User.vue,但是当我尝试访问 /user/profile
或 /user/settings
时,[=56] 中不会呈现任何内容=].我关注了 /user
路线上呈现,并且当我们在 /user/profile
路线上时只应该呈现 Profile.vue
的内容。我试图在 User.vue
中包含 <router-view />
,但我在 /user/profile
中同时获得了 User.vue
和 Profile.vue
内容。我附上了 codesandbox link 以实时查看它并获得更好的理解,因为我不确定如何在 SO 中设置它。
Link: https://codesandbox.io/s/nostalgic-sky-3wvhqr?file=/App.vue:0-354
我怎样才能做到这一点?
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
}
]
}
]