我以前有一个字符串可以包含我接受的 HTML(来自服务器,而不是用户)作为 Prop 。简单来说,大概是这样的。
<foobar alert-content="<strong>bazboo</strong>">
</foobar>
然后我定义了 prop 使其成为必需的
alertContent: {
type: String,
required: true,
},
我认为槽在这里更有意义,所以我开始传递它是一个槽。
<foobar>
<strong>bazboo</strong>
</foobar>
如您所料,模板中有一个插槽。它有效。但我不能再要求它了。
我如何在 Vue.js 中要求插槽?
最佳答案
我不知道有任何内置方法可以像需要 prop 一样需要插槽,但是您可以通过在创建组件时检查默认插槽来相当轻松地提供相同的功能。
这是一个例子。
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>
或者提供默认内容,使其明显需要提供插槽。
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>
关于javascript - 如何在 Vue.js 中要求插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180238/