[英]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. 我之前有一个字符串可以包含HTML(来自服务器,而不是用户),我接受它作为道具。 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? 我如何在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.