In Vue.js, adding dynamic class names is a common requirement that can be implemented using the :class binding. :class is a special directive provided by Vue.js that dynamically toggles the element's class based on data changes. Here are some common methods to use :class for adding dynamic class names:
1. Object Syntax
You can pass an object to :class. The keys represent the class names you want to apply, and the values are boolean expressions that determine whether the class should be applied to the element. For example:
html<template> <div :class="{ active: isActive, 'text-danger': hasError }"></div> </template> <script> export default { data() { return { isActive: true, hasError: false } } } </script>
In this example, if isActive is true, the active class will be applied to the div; if hasError is also true, the text-danger class will also be applied.
2. Array Syntax
:class can also accept an array, allowing you to apply multiple class names to the same element. You can combine string literals with objects:
html<template> <div :class="['base-class', { active: isActive, 'text-danger': hasError }]"></div> </template> <script> export default { data() { return { isActive: false, hasError: true } } } </script>
In this example, base-class is always applied, while active and text-danger are applied based on the corresponding boolean values.
3. Computed Properties
When the logic for class names becomes complex, using computed properties simplifies the template. This approach moves the logic to JavaScript, making the template clearer:
html<template> <div :class="classObject"></div> </template> <script> export default { data() { return { isActive: true, hasError: true } }, computed: { classObject() { return { active: this.isActive && !this.hasError, 'text-danger': this.hasError }; } } } </script>
In this example, the classObject computed property dynamically returns an object based on the values of isActive and hasError, which determines which class names should be applied to the div.
In summary, Vue.js's :class binding provides a flexible and powerful way to dynamically handle HTML element class names, making it simple and intuitive to adjust styles based on data changes.