首頁  >  文章  >  web前端  >  詳解Vue-router子路由(嵌套路由)如何創建

詳解Vue-router子路由(嵌套路由)如何創建

藏色散人
藏色散人轉載
2022-08-10 10:48:431917瀏覽

在應用程式介面開發中通常由多層巢狀的元件組合而成。但隨著頁面的增多,如果把所有的頁面都塞到一個 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子路由(嵌套路由)如何創建的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除