DEV Community

loading...
Cover image for Vue.js 101 - Dynamic Classes and Computed Properties

Vue.js 101 - Dynamic Classes and Computed Properties

ericchapman profile image Eric Chapman ・2 min read

Follow me on Twitter:

Everyday I publish what I learn the day before from my Vue.js course.

Click follow if you want to miss nothing.

Without further ado here is a summary of my notes for that day.

Binding HTML Classes

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 v-bind to 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 when v-bind is used with class and style. In addition to strings, the expressions can also evaluate to objects or arrays.

We can pass an object to v-bind:class to dynamically toggle classes:

<div :class="{ active: person.isActive }">
  This is the menu option
</div>
Enter fullscreen mode Exit fullscreen mode

In that example Vue will set the class to "active" only if the Vue data object person.isActive equal true

The bound object doesn’t have to be inline. You can reference the whole object directly:

<div :class="classObject">
  This is the menu option
</div>
Enter fullscreen mode Exit fullscreen mode

Vue will replace the classObject with the object properties that are equal to true:

data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}
Enter fullscreen mode Exit fullscreen mode

Computed properties

Computed properties allow us to define a property that is used the same way as data, but can also have some custom logic that is cached based on its dependencies. You can consider computed properties another view into your data.

const app = Vue.createApp({
    data() {
        return {
            people: [
                { name: 'Mike Taylor', email: 'mike@example.com', isActive: true},
                { name: 'John Carson', email: 'john@example.com', isActive: false},
                { name: 'Peter Sanders', email: 'peter@exemple.com', isActive: true}
            ],
        }
    },
    computed: {
        activePeople() {
            return this.people.filter((person) => person.isActive)
        }
    }
})
Enter fullscreen mode Exit fullscreen mode

This computed property can be use like data:

<div v-for="person in activePeople" :key="person.name">
      {{ person.name }} : {{ person.email }}  
</div>
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it for today. Tomorrow the journey continue, see you later! If you want to be sure to miss nothing click follow me here or on twitter!

Follow me on Twitter:

Discussion (0)

pic
Editor guide