Categories
Vue Answers

How to apply multiple conditional classes in Vue.js?

Spread the love

In Vue.js, we can apply multiple conditional classes to an element using either the object syntax or array syntax within the v-bind:class directive.

To do this we can do the following:

Using Object Syntax:

<template>
  <div :class="{ 'class1': condition1, 'class2': condition2, 'class3': condition3 }">
    <!-- Content -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      condition1: true,
      condition2: false,
      condition3: true
    };
  }
};
</script>

In this example, the classes class1, class2, and class3 are conditionally applied based on the values of condition1, condition2, and condition3.

Using Array Syntax:

<template>
  <div :class="[condition1 ? 'class1' : '', condition2 ? 'class2' : '', condition3 ? 'class3' : '']">
    <!-- Content -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      condition1: true,
      condition2: false,
      condition3: true
    };
  }
};
</script>

In this example, each class is conditionally added to the array if its respective condition evaluates to true.

Dynamic Classes with Computed Properties:

Alternatively, we can use computed properties to determine the classes dynamically based on certain conditions:

<template>
  <div :class="computedClasses">
    <!-- Content -->
  </div>
</template>

<script>
export default {
  computed: {
    computedClasses() {
      return {
        'class1': this.condition1,
        'class2': this.condition2,
        'class3': this.condition3
      };
    },
    data() {
      return {
        condition1: true,
        condition2: false,
        condition3: true
      };
    }
  }
};
</script>

In this approach, the computedClasses computed property returns an object with the class names as keys and the conditions as values.

Choose the method that best fits our use case and preference. Each method is effective for applying multiple conditional classes in Vue.js.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *