Implementing a CSS Class in Vue.js

in #vuejs7 years ago

Sometimes during runtime, you have to change the CSS class of the element. While changing the classes, it is best to conditionally apply the details of the style. On the other hand, Vue.JS conditionally applies a CSS class to an element at runtime. For this, JavaScript is used for binding. For finishing this task, you need to do two things –

• First, define your CSS Class
• Make the class binding in the template
- By using object syntax
- By using array syntax

Both the points are explained in detail, below -

Step 1: Define Your CSS Class
The class is defined in the Bootstrap CSS framework. But if it is not defined there, you have to define it somewhere. For identifying the currently selected page, active CSS class is used. The bootstrap CSS also defines the CSS. The third list item elements contain the active class. In order to apply a CSS class conditionally, add a JavaScript object.
Step 2: Make Your Class Bindings
There are two main choices while making template based class binding - using object syntax and using array syntax.

Object syntax binding - JavaScript expression is used to create a class binding using the object syntax. By using v-for directive, which is used to render Items in loop, I reduced the amount of code. The V-bind directive attaches the Vue instance and class attribute of the element.
Active class will be used when the expression is true and it is applied based on the currentPage value.

Array syntax binding – In Vue, one can apply a list of CSS classes by binding to an array. This alternate approach has two extra features in the data object – PageItemClass and ActiveClass. Although the data object has extended, but using arrays help you keep the code template cleaner.

The choice between the object syntax and the array is a personal preference as both of them seem to make the HTML more complicated. But it is much more beyond that. It is about creating a data driven template. These tips will give you a head start in using Vue.JS effectively. For further enhancing your knowledge, explore CodeFights, a one stop junction for all your programming and development query and practice. Visit Today!

Sort:  

Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://www.sitepoint.com/conditionally-applying-css-class-vue-js/