Search code examples
vue.jscomponentsvue-component

Vue - Nesting components without separating into single page


I am new in Vue and try to learn how the component structure works in Vue.
below is my code in codepen.
Nesting Components

<div id="todolist">
    <first-layer>
        <second-layer></second-layer>
    </first-layer>
</div>

<script>
var secondLayer = Vue.extend({
  template: '<div>i am second layer.</div>'
});

var firstLayer = Vue.extend({
  template: '<div>I am first layer.</div>',
  components: secondLayer,
});

var todolist = new Vue({
    el: "#todolist",
    components: {
        'first-layer': firstLayer,
    }
});
<script>

What I try to do is to separate component out of its parent by declare an object then call it in components property. It worked at first layer. But, when I try to do same thing in a component ( like nesting them) with same moves, the second layer didn't show up as expected. Why is that?

And what is the recommended structure to handle these without .vue file sep


Solution

  • This is happening because Vue overrides any template you put inside <first-layer> with the component's template.

    To prevent it, you can use slots:

    var firstLayer = Vue.extend({
      template: '<div>I am first layer1.<slot></slot></div>'
    });
    

    now every content you put between <first-layer> tag will go into this slot.

    If you want a more complicated component with different slots, you can use named slots