Vue-router 第2节 Vue-router配置子路由

Vue-router 第2节 Vue-router配置子路由


第2节 Vue-router配置子路由

这节课学习子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只是部分改变样式。我们接着第一节课的实例,在Hi页面的下面新建两个子页面,分别是 “Hi页面1” 和 “Hi页面2”,来实现子路由。

1. 改造App.vue的导航代码

我们需要改造app.vue的导航代码,来实现基本的导航功能。用<router-link>标签增加了两个新的导航链接。

App.vue代码:

      <p>导航:
        <router-link to="/">首页</router-link>
        <router-link to="/hi">Hi页面</router-link>
        <router-link to="/hi/Hi1">-Hi页面1</router-link>
        <router-link to="/hi/Hi2">-Hi页面2</router-link>
      </p>

再访问主页导航栏已经变了,多出两个子导航:Hi页面1和Hi页面2:

2. 改写components/Hi.vue页面

把Hi.vue改成一个通用的模板,加入<router-view>标签,给子模板提供插入位置。“Hi页面1” 和 “Hi页面2” 都相当于“Hi页面”的子页面,有点像继承关系。我们在“Hi页面”里加入<router-view>标签。

<template>
    <div class="hello">
        <h1>{{ msg }}<router-view /></h1>

        <router-view class="aaa"></router-view>
    </div>
</template>

<script>
export default {
    name: 'hi',
    data(){
        return {
            msg: 'Hi,I am Daisy'
        }
    }
}
</script>

<style scoped>

</style>

3. 在components目录下新建两个组件模板Hi1.vue和Hi2.vue

新建的模板和Hi.vue没有太多的差别,只是改变了data中message的值,也就是输出的结果不太一样了。
Hi1.vue:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
export default {
  name: 'hi',
  data () {
    return {
      msg: 'Hi, I am Hi1!'
    }
  }
}
</script>
<style scoped>

</style>

Hi2.vue:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
export default {
  name: 'hi',
  data () {
    return {
      msg: 'Hi, I am Hi2'
    }
  }
}
</script>
<style scoped>
</style>

4. 修改router/index.js代码

我们现在导航有了,母模板和子模板也有了,只要改变我们的路由配置文件就可以了。子路由的写法是在原有的路由配置下加入children字段

children:[
{path:'/',component:xxx},
{path:'xx',component:xxx},
]

children字段后边跟的是个数组,数组里和其他配置路由基本相同,需要配置path和component。具体看一下这个子路由的配置写法:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Hi from '@/components/Hi'
import Hi1 from '@/components/Hi1'
import Hi2 from '@/components/Hi2'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },{
      path:'/Hi',
      name: 'Hi',
      components: Hi,
      children:[
        {path:'/',component:Hi},
        {path:'hi1',component:Hi1},
        {path:'hi2',component:Hi2},
      ]
    }
  ]
})

需要注意的是,在配置路由文件前,需要先用import引入Hi1和Hi2。

Summary:
这节课学的内容在路由配置里经常用到,比如我们作一个购物模块,购物模块里有很多相同的元素,我们就会利用这种子路由的形式,先定一个父页面,然后再修改子页面。希望这节课对你有帮助,其实子路由的步骤还是有些繁琐的,所以希望你们多练习几遍,能够完全掌握。

原文地址:https://www.cnblogs.com/Elva3zora/p/12711208.html