在应用界面开发中通常由多层嵌套的组件组合而成。但随着页面的增多,如果把所有的页面都塞到一个 routes 数组里面会显得很乱,你无法确定哪些页面存在关系。借助 vue-router 提供了嵌套路由的功能,让我们能把相关联的页面组织在一起。【相关推荐:vue.js视频教程】
实验目的在我们的商城项目中,后台管理页 admin 涉及到很多操作页面,比如:
/admin 主页面/admin/create 创建新信息/admin/edit 编辑信息让我们通过嵌套路由的方式将它们组织在一起。
创建admin页面在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>
修改router/index.js代码增加子路由,子路由的写法是在原有的路由配置下加入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子路由(嵌套路由)如何创建的详细内容。