我之前有一个字符串可以包含HTML(来自服务器,而不是用户),我接受它作为道具.简化,就是这样的.
<foobar alert-content="<strong>bazboo</strong>">
</foobar>
Run Code Online (Sandbox Code Playgroud)
我定义了道具,使其成为必需品
alertContent: {
type: String,
required: true,
},
Run Code Online (Sandbox Code Playgroud)
我决定在这里更有意义的插槽,所以我开始传递它是一个插槽.
<foobar>
<strong>bazboo</strong>
</foobar>
Run Code Online (Sandbox Code Playgroud)
您可以在模板中使用插槽.它有效.但我不能再要求了.
我如何在Vue.js中需要一个插槽?
我不知道有任何内置方式要求插槽的方式与需要支撑的方式相同,但是通过在创建组件时检查默认插槽,您可以相当容易地提供相同的功能.
这是一个例子.
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"
})Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<test-component></test-component>
</div>Run Code Online (Sandbox Code Playgroud)
或者提供默认内容,使得显而易见的是需要提供插槽.
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"
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)