三十三、vue-router配置子路由

版权声明:本文为博主原创文章,未经博主允许欢迎转载,请注明原文链接。一起交流,共同进步。 https://blog.csdn.net/newbie_907486852/article/details/83478964

                             vue-router配置子路由

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

1、 App.vue代码

      我们需要先改造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>

2、改写components/Hi.vue页面

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

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

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

      新建的模板和Hi.vue没有太多的差别,知识改变了data中message的值,也就是输出的结果不太一样了。
Hi2.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字段后边跟的是个数组,数组里和其他配置路由基本相同,需要配置path和component。具体看一下这个子路由的配置写法。

import Vue from 'vue'   
import Router from 'vue-router'  
import Hello from '@/components/Hello'  
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: 'Hello',     
      component: Hello   
    },{
      path:'/hi',
      component:Hi,
      children:[
        {path:'/',component:Hi},
        {path:'hi1',component:Hi1},
        {path:'hi2',component:Hi2},
      ]
    }
  ]
})

猜你喜欢

转载自blog.csdn.net/newbie_907486852/article/details/83478964
今日推荐