子视图组件将支持传递给Vue中的父布局

时间:2018-04-30 13:35:31

标签: vue.js vuejs2 vue-component vue-router

TL; DR:是否可以从子组件中将内容传递到父组件中引用的组件的特定插槽?

我正在使用Vue Webpack Template附带的Vue Router,它提供了开箱即用的单页应用程序的基础。

我面临的问题是,我有一个主布局,简化如下:

<template>
  <div id="app">
    <Nav/>
    <APageWithDifferentNav/>
  </div>
</template>

<script>
  import Home from "./components/views/Home";
  import APageWithDifferentNav from "./components/views/APageWithDifferentNav";
  import Nav from "./components/Nav";

  export default {
    name: "App",
    components: {
      Nav, Home, APageWithDifferentNav
    }
  };
</script>

导航组件是这样的:

<template>
  <div class="nav">
    <ul class="nav__list">
      <li class="nav__list-item">always show this nav item</li>
    </ul>
    <slot>
      <ul class="nav__list replace-this">
        <li class="nav__list-item">only show this</li>
        <li class="nav__list-item">if no slot</li>
        <li class="nav__list-item">content provided</li>
      </ul>
    </slot>
  </div>
</template>

<script>
  export default {
    name: "Nav"
  };
</script>

我希望能够在视图组件中更改Nav组件中的插槽。

例如,在结帐或入职流程中,您希望限制向用户显示的导航选项,并交换其他内容以突出显示他们的旅程。

有没有办法让我这样做,而不必在每个页面的模板中移动<Nav/>

I've put together a more indepth code example to show what I'm after which you can view here.

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

AFAIK只能将插槽内容从父级传递给子级。

也许你可以使用PortalVue获得类似的东西,它可以在定义组件之外渲染DOM,并使用一些v-if来禁用默认部分的渲染。

但它似乎是一种过度设计的解决方案。有时最好打破DRY原则(不要重复自己)并从每个页面调用导航组件,必要时进行变换,或者只是为具有不同导航的少数视图创建完全不同的页面,例如{{ 1}},/login,...并在顶层使用dynamic componentsv-bind:is来选择要呈现的视图组件(因此您有一个常用的App组件用于所有常规页面,使用常规Nav组件,以及使用不同LoginLogoutNav的一个(或多个必要的)备用LoginLogoutApp组件。