2

I'm trying to understand the usage of <slot> in Vue templates. The way I understand it, slots can be used to pass along child content in the component to the template.

Below is a short, minimum working example (also on codepen).

Vue.component('mine', {
  template: '#mine'
})

var app = new Vue({
  el: '#app' 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>

<script type="text/x-template" id="mine">
  <h1>this is it</h1>
  <slot></slot>
</script>

<div id="app">
  <mine>
    <p>why isn't this displayed</p>
  </mine>
</div>

I would expect the output to be like this:

<h1>this is it</h1>
<p>why isn't this displayed</p>

However, what happens is the second line does not appear when the page is rendered.

tony19
  • 125,647
  • 18
  • 229
  • 307
Scribblemacher
  • 1,518
  • 1
  • 16
  • 31

1 Answers1

5

Templates need to have a single root DOM element. Looks like Vue was just taking the h1 as the whole template and discarding the rest:

Vue.component('mine', {
  template: '#mine'
})

var app = new Vue({
  el: '#app' 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>

<script type="text/x-template" id="mine">
  <div>
    <h1>this is it</h1>
    <slot></slot>
  </div>
</script>

<div id="app">
  <mine>
    <p>why isn't this displayed</p>
  </mine>
</div>

(Using a "developer mode" version of the library will give you better error messages about this sort of thing:)

Vue.component('mine', {
  template: '#mine'
})

var app = new Vue({
  el: '#app' 
})
<script src="https://vuejs.org/js/vue.js"></script>

<script type="text/x-template" id="mine">
    <h1>this is it</h1>
    <slot></slot>
</script>

<div id="app">
  <mine>
    <p>why isn't this displayed</p>
  </mine>
</div>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • 1
    Thanks for the tip on a development build; this is extremely helpful. In trying to learn Vue, I've scratched my head at a number of things that don't work but also don't throw errors or warnings. – Scribblemacher Mar 07 '18 at 14:34
  • Yeah, dev mode in vue has unusually good error messages; I wish other frameworks took as much care about that sort of thing. – Daniel Beck Mar 07 '18 at 14:38