[Vuejs]-Vuejs: weird class render

1👍

The problem is here:

<component v-for="item in List" 
                :item="item"
                :class="item.class"
                :name="item.name">
</component>

In this section you’re binding the class to item.class and the attribute name to item.name. Vue will apply both of these to the outer element of the corresponding component.

Within that component you’re then adding :class="item.class", which adds the class again.

To fix this just remove the :class="item.class" and :name="item.name" from that first template.

<component v-for="item in List" 
                :item="item">
</component>

It is also a little mysterious that you have List defined within the data of component but you seem to be using it within the scope of the parent component’s template.

Update based on a comment:

A class can be set on the outer element in two ways. It can either come from the component itself, inside its template, or it can be set from the parent template.

Which one you choose depends on what the class does and which of the two components is responsible for that. Neither one is necessarily right or wrong.

Usually a component is responsible for controlling its own styling but a common exception to that is classes that control layout.

For example, if you have a button component then classes that decide whether the button should be red, green or blue would typically be managed by the component itself. However, if that button needs to be right-aligned within its parent container then the button component probably doesn’t need to know about that. That alignment decision is controlled by the parent container and it can set a class on the button without the button needing to get involved.

Leave a comment