Vue-Router 命名视图

同时 (同级) 展示多个视图

by logan70

HTML

<script src="https://cdn.bootcss.com/vue/2.5.17/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>

<div id="app">
  <h1>Vue-Router 命名视图</h1>
  <p>
    <!-- 路由导航,to属性决定导航地址 -->
    <!-- router-link编译后默认渲染为a标签 -->
    <router-link to="/home">主页</router-link>
    <router-link to="/user">个人页</router-link>
  </p>
  <!-- 路由渲染出口 -->
  <router-view></router-view>
  <router-view name="viewA"></router-view>
  <router-view name="viewB"></router-view>
</div>

JavaScript

const Home = {template: '<div><p>主页(Home组件)</p></div>'}
const User = {template: '<div><p>个人页(User组件)</p></div>'}
const Child = {template: '<div><p>主页B组件的默认子组件(Child组件)</p></div>'}

const HomeA = {template: '<div><p>主页A组件</p></div>'}
const HomeB = {template: `
    <div>
      <p>主页B组件</p>
      <router-link to="/home/child">主页B组件的嵌套命名视图</router-link>
      <router-view></router-view>
      <router-view name="view"></router-view>
    </div>
  `
}

const UserA = {template: '<div><p>个人页A组件</p></div>'}
const UserB = {template: '<div><p>个人页B组件</p></div>'}

const ChildC = {template: '<div><p>主页B组件的子组件C</p></div>'}

const router = new VueRouter({
  routes : [
    {
    	path: '/home',
      components: {
      	default: Home,
        viewA: HomeA,
        viewB: HomeB
      },
      children: [
      	{
        	path: 'child',
          components: {
          	default: Child,
            view: ChildC
          }
        }
      ]
    },
    {
    	path: '/user',
      components: {
      	default: User,
        viewA: UserA,
        viewB: UserB
      }
    }
  ]
})

const app = new Vue({
  router
}).$mount('#app')