[英]How to apply CSS class to child component with two root nodes?
我使用 Vue 3 和带有两个根节点的 Vuetify 3 创建了一个自定义警报组件
<template>
<v-alert type="warning" title="Contains button to display dialog" />
<v-dialog>dialog goes here</v-dialog>
</template>
v-alert
组件包含一个按钮,用于切换v-dialog
组件的 state。
在我的父组件(消费组件)中,我想将 CSS class 应用于子组件(我的自定义警报组件)
<MyAlert class="mb-8" />
<div>Main content goes here</div>
问题是这不起作用,我收到警告
[Vue warn]: Extraneous non-props attributes (class) were passed to component but couldn't be automatically inherited because component renders fragment or text root nodes 外来的非道具属性(类)被传递给组件但无法自动继承,因为组件呈现片段或文本根节点
这是有道理的,因为它不知道哪个组件应该有这个 class,两者都是,警报或对话框或没有。
快速解决方法是将 class mt-8
应用于下面的div
。 但是我的警报组件是有条件的,所以我必须使用 if 语句来检查我是否应该应用边距顶部。
是否可以告诉 Vue 它应该将应用的 class 用于内部v-alert
组件?
是的你可以! 您需要做的第一件事是指定
继承属性:假
警报组件中的选项:
<script>
export default {
inheritAttrs: false,
}
</script>
然后您可以将 class 属性应用于所需的组件
:class="$attrs.class"
但是你必须知道,现在每个其他属性都必须在代码中使用 $attrs 指定,因为你的组件将不再默认应用它们
有关此主题的更多信息,请参见Vue Docs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.