仅在有内容时才显示插槽 [英] Only show slot if it has content
问题描述
有没有办法只显示有内容的插槽?
例如,我正在构建一个简单的 Card.vue
组件,如果页脚插槽有内容,我只希望显示页脚:
模板:
<div class="panel" :class="panelType"><div class="panel-heading"><h3 class="panel-title"><插槽名称=标题">默认标题</slot>
<div class="panel-body"><插槽名称="body"></插槽><p class="类别"> <div class="panel-footer" v-if="hasFooterSlot"><slot name="footer"></slot>
</模板>
脚本:
在视图中:
由于上面的组件不包含页脚,它不应该被渲染,但它是.
我尝试过使用 this.$slots['footer']
,但这返回 undefined.
有人有什么建议吗?
应该可以在
this.$slots.footer
所以,这应该可行.
hasFooterSlot() {返回 !!this.$slots.footer}
示例.
Is there a way to only display a slot if it has any content?
For example, I'm building a simple Card.vue
component, and I only want the footer displayed if the footer slot has content:
Template:
<template>
<div class="panel" :class="panelType">
<div class="panel-heading">
<h3 class="panel-title">
<slot name="title">
Default Title
</slot>
</h3>
</div>
<div class="panel-body">
<slot name="body"></slot>
<p class="category">
<slot name="category"></slot>
</p>
</div>
<div class="panel-footer" v-if="hasFooterSlot">
<slot name="footer"></slot>
</div>
</div>
</template>
Script:
<script>
export default {
props: {
active: true,
type: {
type: String,
default: 'default',
},
},
computed: {
panelType() {
return `panel-${this.type}`;
},
hasFooterSlot() {
return this.$slots['footer']
}
}
}
</script>
In in View:
<card type="success"></card>
Since the above component doesn't contain a footer, it should not be rendered, but it is.
I've tried using this.$slots['footer']
, but this returns undefined.
Does anyone have any tips?
It should be available at
this.$slots.footer
So, this should work.
hasFooterSlot() {
return !!this.$slots.footer
}
这篇关于仅在有内容时才显示插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!