Vue.js Tutorial: Data & Event Binding, Bind Data, Classes, Styles, Conditionally

It's time to write first lines of Vue code! We prepare all necessary data, and bind them into HMTL template, with using string interpolation, class, style and attribute binding. Depending on data values, we hide/show some boxes conditionally.

JavaScript tab in JSFiddle is already presented and prefilled with some lines of Vue code.

Do you remember complete HTML template, we have prepared before? In the Result tab, only couple of elements remained visible, others are hidden, because the game hasn’t started yet.

Custom CSS changed also a bit. Take a look at the example, open it in JSFiddle, try to change some data properties, and then explanation follows, what really happened.

Vue Data Binding Example

Data binding Explanation

My and Bank amount of money is displayed by simple string interpolation. The same value is used in progress bars to manipulate the colory width by inline CSS.

I also bind different Bootstrap classes to the progress bar, depending on the money available. The HTML element already has some classes, but it doesn’t mean, that two “class” attributes are made.

Vue merge them together, when you explore the console (and change amount of money), you can see perfectly valid HTML structure.

The button “Start New Game” is conditionally displayed only if game is over, or you just run the app for the first time.

I use the same data property to display playground, if you wish to play. Starting button disappears and game is ready! Now, turn “gameIsOn” data property to true to see in real.

In string interpolation you can even use JavaScript expressions, e.g. terniary operator. This is how our content of the random number HTML element looks like:

{{ randomNumber ? randomNumber : ' ' }}

Perfectly valid, as well as comparison or even more complicated functions.

Different (pseudo)attributes are bound to input (readonly), paragraph “on number from each range” (hidden) and playing buttons (disabled) to manage a game.

Input Validation

Firstly, I prepared validation message right below the input. I bind a class “is-invalid” conditionally to the input. That’s all.

I show you the business logic in the next, last part of the tutorial, but don’t be confused, that on the warning message is not any Vue attribute, or class binding presented.

This is simply Bootstrap 4 styling, so explore documentation, if you want to the find more information about the CSS.

Summary

Open Vue example in JSFiddle and play with data properties to see the effect on the HTML template.

In the last part of the tutorial, I write couple of methods to manipulate with data, actually gambling game dynamically.