Vue中router-view和子路由的使用方法

  • Post author:
  • Post category:vue


应用场景:实现一个随着切换tab栏,头部底部不变,中间内容变得功能需求。


首先需要在路由文件中添加子路由(children):

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import Content1 from '@/views/Content1.vue'
import Content2 from '@/views/Content2.vue'
import Content3 from '@/views/Content3.vue'
import Content4 from '@/views/Content4.vue'
Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      children: [
        {
          path: '/content1',
          name: 'content1',
          component: Content1
        },
        {
          path: '/content2',
          name: 'content2',
          component: Content2
        },
        {
          path: '/content3',
          name: 'content3',
          component: Content3
        },
        {
          path: '/content4',
          name: 'content4',
          component: Content4
        }
      ]
    }
  ]
})

子路由已经创建完毕,分别创建对应的子路由文件,即中间要显示的内容:

在这里插入图片描述

然后在父路由Home.vue文件中,增加router-view块,写法如下:

<template>
  <div class="about" style="background-color: #edeeef;width: 100%;">
    <nav-header />
    <router-view />
    <nav-footer />
  </div>
</template>
<script type="text/javascript">
import NavHeader from '../components/NavHeader'
import NavFooter from '../components/NavFooter'
import Vue from 'vue'
export default {
	name: 'Home'
    components: {
        NavHeader,
        NavFooter
    }
}
</script>

tab栏写在NavHeader.vue文件内

<template>
   <div style="background-color: red;font-size: 0.15rem;">
     这是header
     <div class="tab">
        <router-link to="/content1">content1</router-link>
        <router-link to="/content2">content2</router-link>
        <router-link to="/content3">content3</router-link>
        <router-link to="/content4">content4</router-link>
     </div>
   </div>
</template>
<style type="text/css">
  .tab{
    display: flex;
    justify-content: space-between;
  }
</style>
<script>
export default {
  name: 'NavHeader'
}
</script>

然后就可以随着切换不同的tab选项,渲染不同的子路由文件内容了,且header和footer不变:

简单的demo示例如下:

在这里插入图片描述

在这里插入图片描述



版权声明:本文为weixin_44212165原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。