Using dynamic component with slots inside Layout component

245 views Asked by At

Is it possible to have a dynamic component inside a LayoutComponent that uses slots to display contents? To explain: LayoutComponent uses slots to arrange & style contents using slots. To have multiple pages use the LayoutComponent, instead of wrapping each Page Components template with LayoutComponent, is it possible to have a single instance of LayoutComponent and have a dynamic component inside it?

https://codesandbox.io/s/reverse-slot-qft2n7?file=/src/main.js

Above link has the current code and also has the desired template commented out. Any idea if its achievable?

Googled, tried to use a component using render etc., Nothing seems to work.

1

There are 1 answers

1
summerisbetterthanwinter On

You have just edit a little your code

You can do it like this

import Vue from "vue";

Vue.config.productionTip = false;

const LayoutComponent = {
  template: `<div>
    <div style="border: solid red 1px; margin-bottom:10px">
    <slot name="default"></slot>
    </div>
    <div style="border: solid green 1px">
    <slot name="footer"></slot>
    </div>
  </div>`
};

const PageOne = {
  components: {
    LayoutComponent
  },
  template: `
  <div>This is content One</div>
  <div slot="footer">This is footer One</div>
  `
};

const PageTwo = {
  components: {
    LayoutComponent
  },
  template: `
  <div>This is content Two</div>
  <div slot="footer">This is footer Two</div>
  `
};

new Vue({
  data() {
    return {
      showOne: true
    };
  },
  computed: {
    currentComp() {
      return this.showOne ? PageOne : PageTwo;
    }
  },
  template: `
  <div>
  <button @click="showOne = !showOne">Switch</button>
  <layout-component>
    <component :is="currentComp"></component>
  </layout-component>
  </div>
  `
  //Desired template:
  // <layout-component><component :is="currentComp"></component></layout-component>
}).$mount("#app");