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 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?
Share Improve this question asked May 4, 2018 at 17:26 GooseGoose 4,8335 gold badges51 silver badges90 bronze badges 3- What behavior do you expect if it isn't there? – Bert Commented May 4, 2018 at 17:36
- The same behavior as when I fail to pass in a required prop would be ideal. – Goose Commented May 4, 2018 at 17:37
- 1 Hah, provide one default slot content which warning the developer... – Sphinx Commented May 4, 2018 at 17:43
1 Answer
Reset to default 11I'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 ponent is created.
Here is an example.
console.clear()
Vue.ponent("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./ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<test-ponent></test-ponent>
</div>
Alternatively provide default content that makes it obvious the slot needs to be provided.
console.clear()
Vue.ponent("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./ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<test-ponent></test-ponent>
<hr>
<test-ponent>
<h3>This one won't show the default content</h3>
</test-ponent>
</div>