在特定页面上插入不同块的页面的 Vue App 布局

Vue App layout for pages with insertion of different blocks on a specific page

我有一个 vue 项目:

App.vue
layouts 
---- DefaultLayout.vue
views
---- Home.vue
---- About.vue
....

DefaultLayout.vue:

<template>
  <span>
    <div class="change">
      <slot/>
    </div>
    <b-container>
      <router-view></router-view>
    </b-container>
  </span>
</template>
<script>
export default {
  name: "DefaultLayout"
};
</script>

Home.vue:

<template>
  <div>
    <div class="change">
      <h1>Default layout</h1>
    </div>
    <h2>Default Layaout > Home</h2>
    <router-link :to="{ name: 'Intro', params: { id: intro }}">intro</router-link>
  </div>
</template>

<script>
import DefaultLayout from "../layouts/DefaultLayout";

export default {
  name: "Home",
  components: {
    DefaultLayout
  }
};
</script>

About.vue:

<template>
  <div class="change">
    <h2>Default Layaout > About</h2>
  </div>
</template>
<script>
import DefaultLayout from "../layouts/DefaultLayout";

export default {
  name: "about",
  components: {
    DefaultLayout
  }
};
</script>

重点是为页面(视图)制作一个总体布局,但能够更改特定块(class = "change")。对于主页,一个内容,对于关于,另一个,但是页面的总体框架。

现在:

<div id="app">
  <span>
    <div class="change"></div>
    <div class="container">
      <div>
        <div class="change">
          <h1>Default layout</h1>
        </div>
        <h2>Default Layaout &gt; Home</h2>
        <a href="#/" class="router-link-active">intro</a>
      </div>
    </div>
  </span>
</div>

它应该是(没有双 change):

<div id="app">
  <span>
    <div class="container">
      <div>
        <div class="change">
          <h1>Default layout</h1>
        </div>
        <h2>Default Layaout &gt; Home</h2>
        <a href="#/" class="router-link-active">intro</a>
      </div>
    </div>
  </span>
</div>

codesandbox

问题:如何使用slot(特定位置的不同插入)为应用程序视图(页面)格式化布局(页面的通用模板框架) ?

您可以使用 vue-router 中的命名视图:https://router.vuejs.org/guide/essentials/named-views.html

您将拥有更改部分的视图,其余部分的默认视图。

在您的布局中:

<div class="change">
     <router-view name="title">
</div>

每个部分都有自己的组成部分,例如 AboutAboutTitle

然后在路由器配置中:

routes = [
  {
    path: "/",
    name: "DefaultLayout",
    component: DefaultLayout,
    children: [
      {
        path: "about",
        name: "About",
        title: "About",
        components: {
            default: About,
            change: AboutTitle,
        },
      },
    ]
  },
]

或者,您可以在 DefaultLayout:

中使用插槽
<div class="change">
    <slot name="title"></slot>
</div>
<slot></slot>

并直接在您的页面中使用 DefaultLayout

<DefaultLayout>
    <template #title><h1>About title</h1></template>
    <h2>About content</h2>
</DefaultLayout>

在路由配置中,你不会声明 DefaultLayout:

routes = [
    {
        path: "/about",
        name: "About",
        title: "About",
        components: {
            default: About,
            change: AboutTitle,
        },
    },
]

然而,第二个选项有一个缺点:DefaultLayout 将在页面更改时重新创建。