vue-router子路由的实现

在应用界面开发中通常由多层嵌套的组件组合而成。但随着页面的增多,如果把所有的页面都塞到一个 routes 数组里面会显得很乱,你无法确定哪些页面存在关系。借助 vue-router 提供了嵌套路由的功能,让我们能把相关联的页面组织在一起。


实验目的

在我们的商城项目中,后台管理页 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/Createh1>
        div>
      div>
    template>
    
  • Edit.vue

    <template>
      <div>
        <div class="title">
          <h1>This is Admin/Edith1>
        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 子路由(嵌套路由)创建完成


感谢大家的耐心阅读,如有建议请私信或评论留言

你可能感兴趣的:(前端,#,Vue,vue.js,javascript)