Home > database >  How to apply CSS class to child component with two root nodes?
How to apply CSS class to child component with two root nodes?

Time:12-30

I created a custom alert component using Vue 3 with Vuetify 3 with two root nodes

<template>
  <v-alert type="warning" title="Contains button to display dialog" />
  <v-dialog>dialog goes here</v-dialog>
</template>

The v-alert component contains a button to toggle the state of the v-dialog component.

In my parent component ( the consuming one ) I would like to apply a CSS class to the child component ( my custom alert component )

<MyAlert  />
<div>Main content goes here</div>

The problem is that this doesn't work, I get the warning

[Vue warn]: Extraneous non-props attributes (class) were passed to component but could not be automatically inherited because component renders fragment or text root nodes

Which makes sense because it doesn't know which component should have this class, both, either alert or dialog or none.

A quick fix would be to apply the class mt-8 to the div below. But my alert component is conditional so I would have to use an if-statement to check if I should apply a margin-top or not.

Reproduction link: enter image description here

CodePudding user response:

Yes you can! First thing you need to do is to specify the

inheritAttrs: false

option in your alert component:

<script>
  export default {
   inheritAttrs: false,
  }
</script>

and than you can apply class attribute to the desired component using

:

But you must know, that now every other attribute must be specified in code using $attrs, because your component would not apply them by default anymore

More on this topic can be found here Vue Docs

  • Related