据我了解 Vue 2+,当插槽内容发生变化时,应该重新渲染组件。在我的情况下,我有一个 error-message 组件应该隐藏,直到它有一些插槽内容要显示。起初,我将此方法附加到组件根元素的v-if 上(computed 属性不起作用,Vue 似乎对this.$slots 没有反应性)。
checkForSlotContent() {
let checkForContent = (hasContent, node) => {
return hasContent || node.tag || (node.text && node.text.trim());
}
return this.$slots.default && this.$slots.default.reduce(checkForContent, false);
},
当 99% 的更改发生在插槽中时,这很有效,包括任何添加或删除 DOM 元素。唯一的边缘情况是这样的用法:
<error-message> {{someErrorStringVariable}} </error-message>
这里只更新了一个文本节点,由于我仍然不清楚的原因,我的方法不会触发。我通过连接beforeUpdate() 和created() 解决了这个问题,留给我一个完整的解决方案:
<script>
export default {
data() {
return {
hasSlotContent: false,
}
},
methods: {
checkForSlotContent() {
let checkForContent = (hasContent, node) => {
return hasContent || node.tag || (node.text && node.text.trim());
}
return this.$slots.default && this.$slots.default.reduce(checkForContent, false);
},
},
beforeUpdate() {
this.hasSlotContent = this.checkForSlotContent();
},
created() {
this.hasSlotContent = this.checkForSlotContent();
}
};
</script>