Skip to content

vue嵌套布局实现方式

vue嵌套布局实现方式

我们给出一个简单的嵌套布局的例子。假设我们有一个主布局组件 MainLayout.vue,里面包含一个导航条和一个 <router-view> 用于显示嵌套的子组件。再假设我们有一个子组件 ChildComponent.vue

  1. MainLayout.vue:
 1<template>
 2  <div>
 3    <nav>
 4      <!-- Your navigation links here -->
 5      <a href="/">Home</a>
 6      <a href="/child">Child</a>
 7    </nav>
 8
 9    <router-view></router-view> <!-- This is where ChildComponent will be rendered -->
10  </div>
11</template>
12
13<script>
14export default {
15  name: 'MainLayout'
16}
17</script>
18
19<style scoped>
20/* Your CSS styles here */
21</style>
  1. ChildComponent.vue:
 1<template>
 2  <div>
 3    <h2>I'm the child component</h2>
 4    <!-- other child component content -->
 5  </div>
 6</template>
 7
 8<script>
 9export default {
10  name: 'ChildComponent'
11}
12</script>
13
14<style scoped>
15/* Your CSS styles for the child component */
16</style>

现在,你可以在路由配置中设置这个嵌套关系:

 1import Vue from 'vue'
 2import Router from 'vue-router'
 3import MainLayout from '@/components/MainLayout.vue'
 4import ChildComponent from '@/components/ChildComponent.vue'
 5
 6Vue.use(Router)
 7
 8export default new Router({
 9  routes: [
10    {
11      path: '/',
12      component: MainLayout,
13      children: [
14        {
15          path: 'child',
16          component: ChildComponent
17        }
18        // ... other child routes
19      ]
20    }
21  ]
22})

如此,当你访问 /child 路径时,ChildComponent 将会被渲染在 MainLayout<router-view> 位置。

Related Posts

  1. vue组件生命周期
  2. gfast-ui\src\router\index.ts
  3. gfast-ui\src\views\login\index.vue