Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass class as props in vue js?

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>
like image 699
khawar shah Avatar asked Jan 21 '21 12:01

khawar shah


1 Answers

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>
like image 54
Dan Avatar answered Oct 12 '22 22:10

Dan