...

/

Pass Classes Explicitly via Props

Pass Classes Explicitly via Props

Learn to avoid the issues in migration while passing the classes or styles to a component.

We'll cover the following...

The $attrs object now contains all attributes passed to a component, including class and style.

Vue 2

In Vue 2, v-bind=" $attrs" forwards all properties that were passed to a component, but not classes and styles, because these get special treatment and are applied to the component’s root element:

Press + to interact
<!-- InputField.vue -->
<template>
<label>
<input type="text" v-bind="$attrs" />
</label>
</template>
<script>
export default {
inheritAttrs: false
}
</script>

When used like this:

Press + to interact
<InputField id="input-id" class="input-field-class"></InputField>

The InputField component generates this output:

Press + to interact
<label class="input-field-class">
<input type="text" id="input-id" />
</label>

Run the following code and look at the attrs forwarding example in Vue 2:

Note: The code below may take a while to run. When the server starts, go to the app URL to see the output.

import "./examples/attrs-forwarding/attrs-forwarding";
Attrs forwarding example in Vue 2
  • A new Vue instance is created in the attrs-forwarding.js file. This Vue instance renders the AttrsForwardingExample component.

  • The AttrsForwardingExample component renders the AppInput component with the label, class and input-class props and the v-model directive.

  • The AppInput component has inheritAttrs set to false. This means that all values passed to the component that weren’t declared as props aren’t automatically forwarded to the root element. Instead, the ...