pass class as props in vue js?
Asked Answered
J

1

13

This is the parent component I want to send bind :class to two child component

 <TextInput
    :icon="['fa', 'user']"
    type="text"
    placeholder="Name"
    v-model.trim="userDetails.buyer_name.$model"
    :class="{
        'is-invalid': $v.buyer_name.$error,
        'is-valid': !$v.buyer_name.$invalid
    }"
 >

it's the child component here i want the to accept class as props

<template>
   <div class="product-form">
       <fa-icon class="icons" :icon="icon" ></fa-icon>
       <input :type="type" :placeholder="placeholder" /> 
   </div>
</template>
Jonasjonathan answered 21/1, 2021 at 12:19 Comment(7)
you can use inheritAttrs: false in your child component then class will automatically bind with your child componentAcetophenetidin
actually want to class in the child component, I couldn't able to vuelidate because my input field on another componentJonasjonathan
the same work I've done but it still not workingJonasjonathan
What is not working? You can see the demo works so you must have done something different. Give details: what did you do differently? was there an error? etcBirthstone
I took the concept from the demo, not the solution. There isn't any error, passing props from parent to child :error="$v.buyer_name.$error", :isValid="!$v.buyer_name.$invalid" in child copment class has initialize ``` :class="{ 'is-invalid': error, 'is-valid': isValid }"```Jonasjonathan
That looks ok (assuming that comma is not there), did you also define the props in the child component?Birthstone
Only other things I can think of to try are try passing $data.$v instead of just $v, and try using all lowercase props.Birthstone
B
10

You can't use the attribute class as a prop, because it's reserved for rendering the class of the parent element. If you try to do that, you'll get a warning in the console:

"class" is a reserved attribute and cannot be used as component prop.

So use another name, for example childclass:

:childclass="{
  'is-invalid': $v.buyer_name.$error,
  'is-valid': !$v.buyer_name.$invalid
}"

Apply it in the child like:

<input :class="childclass" />

Here's a demo:

Vue.component('child', {
  props: ['childclass'],
  template: `
  <div>
    <input :class="childclass" />
  </div>
  `
})

new Vue({
  el: "#app"
});
.testclass {
  border: 10px solid red;
}
<div id="app">
  <child :childclass="{ testclass: true }"></child>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
Birthstone answered 21/1, 2021 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.