user759235
user759235

Reputation: 2207

Parent attributes not working in Vue component

Not sure if this is default behavior but I'm trying to build a component in Vue and trying to add attributes like id & class but is not present in the rendered code.

Component

<template>
    <input type="text" name="hello" />
</template>

Usage (named md-input)

<md-input class="hello" />

<!-- this will render too wihtout the class attr -->
<input type="text" name="hello" />

Upvotes: 1

Views: 2296

Answers (2)

tony19
tony19

Reputation: 138526

Normally, attributes are passed onto the root element of the component, as seen in this demo.

But that can't happen when there are multiple elements in the component, and you'd see a warning in the browser's console:

[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. 
  at <MdInput class="hello" > 
  at <App>

For that scenario, you could pass on any attribute bindings to the inner input using v-bind="$attrs":

<template>
  <label for="hello">My Input</label>
  <input type="text" name="hello" v-bind="$attrs" />
</template>

demo 2

Upvotes: 2

H&#233;ctor William
H&#233;ctor William

Reputation: 796

That's a weird behavior, what if you put a default class on the component's template?

<template>
    <input type="text" name="hello" class="default" />
</template>


<md-input class="hello" />

<!-- The element should be render like this --> 
<input type="text" name="default hello" />

Upvotes: 0

Related Questions