Home > Back-end >  adding a custom class to the div element
adding a custom class to the div element

Time:05-13

i have a custom component where i am passing some data to render some css styles

like

<title :profile="true" :/>  

in my component

i have a div as:

<div >

i want if my custom class :class is true, i should add a new class called as flexdisplay to it like

<div >

what i am missing here, i tried passing the value to data as false but it just throwing random errors

CodePudding user response:

Lets assume your parent component is like

<title :profile="true" :showClass="true"/> <!-- modified props name from class to showClass

and in your child component, as you said you have a div like below

<div >

what you can do is change the above div to the below format

<div :> <!-- where enableClass will be a computed property

Inside the script tag of your child component, define props and computed properties like below

<script>
export default {
 props: {
  showClass: {
     type: Boolean,
     default: false
  },
 }
 computed: { // The reason I am doing with computed is for better reactivity
  enableClass() {
   return this.showClass;
  }
 }
}
</script>

CodePudding user response:

You can use class condition syntax

<div :active": isActive }"></div>

This will put the active class if the isActive condition is true

Note that you can combine the class and :class attributes to put either class conditionnaly and classic class

<div  :active": isActive }"></div>

For example in your case if you have the boolean class props your component will look like this :

<template>
   <div  :class={"flexdisplay": isClass}>
      ...
   </div>
</template>
<script>
export default {
   props: {
      isClass: {
         type: Boolean,
         default: true
      }
   }
}
</script>

**Note : ** i've changed the class props by isClass to better understand and do not confuse with the class keywork

  • Related