首页 > 解决方案 > 在组件的布局中渲染一个 Vue 插槽

问题描述

我遇到了命名插槽的问题。这似乎应该工作。在下面的代码中,我尝试使用命名插槽“侧边栏”。我希望我的侧边栏插槽内容显示在侧边栏开始和侧边栏结束文本之间,但该插槽中没有显示任何内容。一切都在主插槽中呈现。

这是我的代码。

路线...

{
  path: "/test",
  name: "test",
  meta: {
    layout: "test-layout"
  },
  component: () =>
    import("@/pages/Test.vue")
},

和 App.vue 模板...

<template>
  <div id="app">
    <component  :is="layout">
      <router-view />
    </component>
  </div>
</template>

和测试布局...

<template>
  <div>
    <div>
      <h1>Sidebar starts</h1>
      <slot name="sidebar"/>
      <h1>Sidebar ends</h1>
    </div>
    <div class="container">
      <h1>Content starts</h1>
      <slot/>
      <h1>Content ends</h1>
    </div>
  </div>
</template>

和页面 Test.vue...

<template>
  <test-layout>
    <span slot="sidebar">sidebar slot content {{forecast.todaySummary}}</span>
    <div>main slot content {{forecast.currentSummary}}</div>
  </test-layout>
</template>

<script>
import api from "@/js/web-services";
export default {
  data() {
    return {
      forecast: null
    };
  },
  created() {
    api.getDailyForecast().then(response => {
      this.forecast = response.data;
    });
  }
};
</script>

以及我的 main.js 中的导入

import TestLayout from "./layouts/test-layout.vue";
Vue.component('test-layout', TestLayout);

为什么我的侧边栏插槽不起作用?

更新

如果我摆脱 main.js 中的两行并添加

import TestLayout from "@/layouts/test-layout.vue";

export default {
  components: { TestLayout },

  data() {...

到 Test.vue 然后它工作。

标签: vue.jsvue-router

解决方案


推荐阅读