Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require a slot in Vue.js?

I previous had a string that could contain HTML (from server, not user) that I was accepting as a prop. Simplified, it was something like this.

<foobar alert-content="<strong>bazboo</strong>">
</foobar>

And I defined the prop to make it required like so

alertContent: {
  type: String, 
  required: true,
},

I decided a slot made more sense here, so I started passing it was a slot.

<foobar>
    <strong>bazboo</strong>
</foobar>

With a slot in the template as you'd expect. And it works. But I can no longer require it.

How can I require a slot in Vue.js?

like image 604
Goose Avatar asked May 04 '18 17:05

Goose


1 Answers

I'm not aware of any built in way to require a slot in the same way a prop can be required, but you can provide the same functionality fairly easily by examining the default slot when the component is created.

Here is an example.

console.clear()

Vue.component("TestComponent",{
  template: `
    <div>
      <slot />
    </div>
  `,
  created(){
    if (!this.$slots.default)
      console.error("TestComponent requires content be provided in the slot.")
  }
})

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <test-component></test-component>
</div>

Alternatively provide default content that makes it obvious the slot needs to be provided.

console.clear()

Vue.component("TestComponent",{
  template: `
    <div>
      <slot>
        <h2>Hey dummy, you need to add content to TestComponent</h2>
      </slot>
    </div>
  `,
  created(){
    if (!this.$slots.default)
      console.error("TestComponent requires content be provided in the slot.")
  }
})

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <test-component></test-component>
  <hr>
  <test-component>
    <h3>This one won't show the default content</h3>
  </test-component>
</div>
like image 137
Bert Avatar answered Sep 22 '22 23:09

Bert