【问题标题】:Wrap Vue Component into another Vue Component将 Vue 组件包装到另一个 Vue 组件中
【发布时间】:2020-07-02 12:16:24
【问题描述】:

我有一个侧边栏组件,我想使用两次,但其中包含不同的其他组件。

我真的很想这样工作:

<template>
  <Sidebar class="left-0">
    <ExampleComponentA/>
  </Sidebar>
  <Content/>
  <Sidebar class="right-0">
    <ExampleComponentB/>
  </Sidebar>
</template>

Vue 是否有可能,还是我真的需要一个 SidebarLeft 和一个 SidebarRight 组件?

<template>
  <SidebarLeft class="left-0"/> <!-- <ExampleComponentA/> is in this Component -->
  <Content/>
  <SidebarRight class="right-0"/> <!-- <ExampleComponentB/> is in this Component -->
</template>

我为什么要那样做?

好吧,我的侧边栏设置是一样的,只是 content 不同。所以我不需要复制洞边栏。

【问题讨论】:

    标签: javascript vue.js components


    【解决方案1】:

    这是一个沙盒示例:link。

    尝试使用slots 来达到同样的效果。

    // App.vue (Parent component)
    <template>
      <div id="app">
        <HelloWorld msg="Hello Vue in CodeSandbox!"> 
          <random slot="random"/> // Component 2 being called inside Component 1
        </HelloWorld>
      </div>
    </template>
    <script>
    import random from "./components/random";
    import HelloWorld from "./components/HelloWorld";
    
    export default {
      name: "App",
      components: {
        HelloWorld,
        random
      }
    };
    </script>
    
    
    // HelloWorld.vue (Component 1)
    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <slot name="random"></slot>
      </div>
    </template>
    
    <script>
    export default {
      name: "HelloWorld",
      props: {
        msg: String
      }
    };
    </script>
    
    // random.vue (Component 2)
    <template>
      <div>I am random</div>
    </template>
    

    【讨论】:

    • 非常感谢。启发了我。不知道我可以那样做。我要深入了解一下插槽
    猜你喜欢
    • 2020-07-04
    • 2019-12-08
    • 2018-11-20
    • 2019-02-20
    • 1970-01-01
    • 2014-01-18
    • 2021-02-14
    • 2021-08-07
    • 2021-02-16
    相关资源
    最近更新 更多