equaliser
equaliser

Reputation: 171

Wrap Vue Component into another Vue Component

I have a Sidebar-Component, which I want to use twice, but with different other components in it.

I really would like to work like this:

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

Is it possible with Vue or do I really need to have a SidebarLeft and a SidebarRight Component?

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

Why do I want to do this like that?

Well, the settings for my Sidebars are the same, only the content are different. So I dont need to duplicate the hole Sidebar.

Upvotes: 0

Views: 155

Answers (1)

priyanshu sinha
priyanshu sinha

Reputation: 625

Here is a sandbox example: link.

Try using slots to achieve the same.

// 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>

Upvotes: 1

Related Questions