Vue Router 預設都是綁定一個 Component,若想同時綁定多個 Component,則要使用 Named Views。
Version
macOS Mojave 10.14.5
Node 12.4.0
Vue CLI 3.8.4
Vue 2.6.10
Vue-router 3.0.3
Named View
- 點擊
About Both
- Route 為
/about/both
- 同時顯示
AboutUs
與AboutYou
component
About.vue
<template>
<div>
<h1>About</h1>
<router-link to="/about/us">About Us</router-link> |
<router-link to="/about/you">About You</router-link> |
<router-link to="/about/both">About Both</router-link>
<router-view name="default"></router-view>
<router-view name="another"></router-view>
</div>
</template>
第 7 行
<router-view name="default"></router-view>
<router-view name="another"></router-view>
使用 name attribute 設定 <router-view/>
的 view 名稱。
<router-view name="default"></router-view>
與 <router-view></router-view>
意義是一樣的,因此 about-us
與 about-you
component 將顯示在 default
view。
當點擊 About Both
時,我們希望 about-us
component 顯示在 default
view,而 about-you
component 顯示在 another
view。
route.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
children: [
{
path: 'us',
name: 'us',
component: () => import(/* webpackChunkName: "about-us" */ './views/about-us.vue'),
},
{
path: 'you',
name: 'you',
component: () => import(/* webpackChunkName: "about-you" */ './views/about-you.vue'),
},
{
path: 'both',
name: 'both',
components: {
default: () => import(/* webpackChunkName: "about-us" */ './views/about-us.vue'),
another: () => import(/* webpackChunkName: "about-you" */ './views/about-you.vue'),
},
},
],
},
]
})
29 行
{
path: 'both',
name: 'both',
components: {
default: () => import(/* webpackChunkName: "about-us" */ './views/about-us.vue'),
another: () => import(/* webpackChunkName: "about-you" */ './views/about-you.vue'),
},
}
若要使用 named view,則要使用 components
property,為 object,其 key 為 view 名稱。
default
view 顯示about-us
componentanother
view 顯示about-you
component
Conclusion
- 一般而言,一個 route 都會對應一個 component,若想一個 route 同時對應兩個以上 component,則要使用 named view
- 若
<router-view/>
沒使用name
宣告 view 名稱,等同於default
view - 若要使用 named view,要在
route.js
要使用components
property,其 key 為 view 名稱
Sample Code
完整範例可在我的 GitHub 上找到