1. 程式人生 > >Vue學習之三 router 2 子路由

Vue學習之三 router 2 子路由

繼續前面的寫一個子路由

程式碼

  • 新增兩個元件 HiVue1.vue HiVue2.vue
<template>
<div>
<h2> {{msg}} </h2>asfdasfasf1
</div>
</template>

<script>
export default {
  name: 'HI1',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App Hi1'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

<template>
<div>
<h2> {{msg}} </h2>asfdasfasf2
</div>
</template>

<script>
export default {
  name: 'HI2',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App Hi2'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

hiVue.vue中新增 router-view

<template>
<div>
<h2> {{msg}} </h2>asfdasfasf
  <router-view/>
</div>
</template>

<script>
export default {
  name: 'HI',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App Hi'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

appVue中新增routerlinke

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <div><router-link to="/hi">hi頁面</router-link></div>
    <div><router-link to="/">首頁</router-link></div>
    <div><router-link to="/hi/hi1">hi1頁面</router-link></div>
    <div><router-link to="/hi/hi2">hi2頁面</router-link></div>

    <router-view/>
  </div>
</template>
 
<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

index.js中新增子路由 (children)

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

Vue.use(Router)

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