Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing CSS classes dynamically with vue js

I have been using vue for about a month now but one thing that I haven't really been able to do properly yet is this.

so in twig we can do something like this

<th class=" 
  {% if condition %}
      class1
  {% else %}      
      class2
  {% end if %}  
">

<th class="sorting_asc" v-for="col in columns" v-if="col.label == sortKey">
<th class="sorting" v-for="col in columns" v-else>

So my first issue is I can't seem to be able to achieve something similar in Vue js. And secondly where I've written 'v-if="col.label == sortKey"', Can I even access the car col.label outside of the html block (outside the loop). Thank you in advanced

like image 609
TheMan68 Avatar asked Dec 30 '16 05:12

TheMan68


People also ask

How do I add dynamic classes to Vue?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component.

How do I add a conditional class to Vue?

To add a class conditionally to an element in Vue, set the class prop to a JavaScript object where for each property, the key is the class name, and the value is the boolean condition that must be true for the class to be set on the element. The classes are only applied when their respective checkboxes are checked.

How do I make my Vue component dynamic?

To make the component dynamic, we can bind it to a set property with the v-bind directive. Your component is now bound with the component property in the data. If you switch the component to Test2 , it will automatically mount the Test 2 component. Test it out on your browser.

How do I add a class dynamically?

To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript. Approach: The className property used to add a class in JavaScript.


1 Answers

You can do following with vuejs with dynamic styling:

<th v-bind:class="{'class1': condition, 'class2': !condition}">

From documentation:

<div v-bind:class="{ active: isActive }"></div>

The above syntax means the presence of the active class will be determined by the truthiness of the data property isActive. you can as well put simple conditions returning boolean in place of isActive

like image 133
Saurabh Avatar answered Oct 20 '22 17:10

Saurabh