在应用界面开发中通常由多层嵌套的组件组合而成。但随着页面的增多,如果把所有的页面都塞到一个 routes 数组里面会显得很乱,你无法确定哪些页面存在关系。借助 vue-router 提供了嵌套路由的功能,让我们能把相关联的页面组织在一起。【相关推荐:vue.js视频教程】
在我们的商城项目中,后台管理页 Admin 涉及到很多操作页面,比如:
/admin 主页面/admin/create 创建新信息/admin/edit 编辑信息让我们通过嵌套路由的方式将它们组织在一起。
在src/views下创建 Admin.vue,并创建admin目录,以用来存放admin的子页面( 使用vue-router的子路由,需要在父组件利用 router-view占位 )
Admin.vue
立即学习“前端免费学习笔记(深入)”;
<template>
<div class="title">
<h1>{{ msg }}</h1>
<!-- 路由插槽 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "home",
data() {
return {
msg: "This is the Admin Page",
};
},
};
</script>
<style scoped>
</style>在src/views下创建admin目录用来存放admin的子页面,在admin目录下新建Create.vue 和 Edit.vue 来实现/create 创建新的商品/edit 编辑商品信息
Create.vue
<template>
<div>
<div class="title">
<h1>This is Admin/Create</h1>
</div>
</div>
</template>Edit.vue
<template>
<div>
<div class="title">
<h1>This is Admin/Edit</h1>
</div>
</div>
</template>增加子路由,子路由的写法是在原有的路由配置下加入children字段。
children:[
{path:'/',component:xxx},
{path:'xx',component:xxx}]注意:children里面的path 不要加 / ,加了就表示是根目录下的路由。
index.js
import Vue from 'vue'import VueRouter from 'vue-router'import Admin from '@/views/Admin.vue'// 导入admin子路由import Create from '@/views/admin/Create';import Edit from '@/views/admin/Edit';Vue.use(VueRouter)const routes = [
{
path: '/admin',
name: 'Admin',
component: Admin,
children: [
{
path: 'create',
component: Create,
},
{
path: 'edit',
component: Edit,
}
]
}]const router = new VueRouter({
routes})export default router至此 Vue-router 子路由(嵌套路由)创建完成
在应用界面开发中通常由多层嵌套的组件组合而成。但随着页面的增多,如果把所有的页面都塞到一个 routes 数组里面会显得很乱,你无法确定哪些页面存在关系。借助 vue-router 提供了嵌套路由的功能,让我们能把相关联的页面组织在一起。
以上就是详解Vue-router子路由(嵌套路由)如何创建的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号