简体   繁体   中英

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM