Vue Data Object

Posted on  by admin

Binding a class on an item and controlling it by the truthy value of a data property is a powerful feature of Vue.js. I will look at a few different ways to do this from binding a class to one item to binding a class to many items at the same time while looking at how it works under the hood.

To start I will look at the problem I encountered and to finish up look at how versatile what we just learnt is. When I tried to add a class to a list item in Vue.js to highlight a selected item, only one item could be checked at a time and an item could not be unchecked either.

See below for what I am talking about. See the PenBasic Vue.js Todo App by Simon (@simonramsay) on CodePen.

This was fine when adding an item or deleting an item but not the intended outcome when checking something off.

Being able to have many items checked off at the same time is what was needed.

In this post, I will guide you through the steps to my solution and try to explain it as clearly as possible. In the below app that I made we have a simple input that when you press enter, on key up a task is added to the tasks array in the data property of our Vue instance.

I also used the same code snippet to delete the tasks by passing the index into the method and using splice().