點燈坊

失くすものさえない今が強くなるチャンスよ

Vue Router 之 Named Views

Sam Xiao's Avatar 2019-06-18

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

view000

  1. 點擊 About Both
  2. Route 為 /about/both
  3. 同時顯示 AboutUsAboutYou 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-usabout-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 component
  • another 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 上找到

Reference

Vue Router, Named Views