Published
danyal.dk
Published
Vue.js: Dynamic class names via v-bind
As defined in vue.js official documentation:
A common need for data binding is manipulating an element’s class list and its inline styles. Since they are both attributes, we can use
Class and Style Bindingsv-bindto handle them: we only need to calculate a final string with our expressions. However, meddling with string concatenation is annoying and error-prone. For this reason, Vue provides special enhancements whenv-bindis used withclassandstyle. In addition to strings, the expressions can also evaluate to objects or arrays.
In this post I will not explain Props/Data or how to write parent and child components, but in case you need more information; take a look at official documentation about props.
Or read my earlier post regarding Single File Component
Let’s look at the basic implementation of v-bind first. We can pass a JSON object to child component or single value could be a String, Number or Boolean.
Following example shows how to add single CSS class to the component
The above syntax means the presence of the active class will be determined by the truthiness of the data property isActive.
Multiple classed can be added to the component, let’s follow the example below.
Template:
Supperting data:
data: {
isPublished: true,
hasError: false
}
It will render when isPublished is true and hasError is false:
As hasError value is changed to false, following will be output
So far we are looking at basic implementation, but what if we need single or multiple class names in v-bind that changes based on props or data value.
Object.vue
Usage of Tree component:
Output will be:
And
This is how you can utilise v-bind for assigning classes & values dynamically.