前面我们製作了 localhost:8080/#/page
的页面
现在我们要製作 localhost:8080/#/page/child1
localhost:8080/#/page/child2
localhost:8080/#/page/child3
三个分页,同样都在 /page
下
首先我们一样先製作元件,src
资料夹底下的 components
资料夹底下的 pages
资料夹的 page.vue
先另存新档为child1.vue,child2.vue,child3.vue
三个档案
接着在 page.vue
档案留下:
<template> <div class="hello"> <div class="card" style="width: 18rem;"> <router-view></router-view> </div> </div></template>
并加上 router-view
在 child1.vue,child2.vue,child3.vue
三个档内留下:
<template> <div class="hello"> <img src="" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card 1</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div></template>
因为我们要更换的是卡片内的内容而已
接着回到 router/index.js
,把元件都载入进来:
import child1 from '@/components/pages/child1'import child2 from '@/components/pages/child2'import child3 from '@/components/pages/child3'
接着在 page
元件路径的地方加上一个 children
属性,放置的内容跟外面的路径物件是一样的:
export default new VueRouter({ routes: [ { ... },{ name: '分页', path: '/page', component: Page,children: [{name: '卡片',path: '',component: child1},{name: '卡片',path: '',component: child2},{name: '卡片',path: '',component: child3}]}]});
这时候如果输入 localhost:8080/#/page/child1
localhost:8080/#/page/child2
localhost:8080/#/page/child3
就能有切换元件的功能了
但我们一样也想有点击连结的功能,所以在 page.vue
再加上 router-link
:
<template> <div class="hello"> <router-link to="/page">卡片1</router-link> <router-link to="/page/child2">卡片2</router-link> <router-link to="/page/child3">卡片3</router-link> <div class="card" style="width: 18rem;"> <router-view></router-view> </div> </div></template>
这时候我们就可以完成点击切换了