Conditionally Applying a CSS Class in Vue.js
There are times you need to change an element’s CSS classes at runtime. But when changing classes, it’s sometimes best to apply style details conditionally. For example, imagine your view has a pager. Pagers are often used to navigate larger sets of items. When navigating, it can be helpful to show the user the page they’re currently on. The style of the item is conditionally set, based on the current page that’s being viewed.
A pager in this case may look something like this:
In this example, there are five pages. Only one of these pages is selected at a time. If you built this pager with Bootstrap, the selected page would have a CSS class named
active applied. You’d want this class applied only if the page was the currently viewed page. In other words, you’d want to conditionally apply the
active CSS class. As discussed in my Vue.js tutorial, Vue provides a way to conditionally apply a CSS class to an element. I’m going to show you this technique in this article.
Step 1: Define Your CSS Classes
Imagine, for a moment, that the five page items shown in the image above were defined using the following HTML:
<div id="myApp"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item active"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">4</a></li> <li class="page-item"><a class="page-link" href="#">5</a></li> </ul> </nav> </div>
Notice that each page in this code snippet has a list item element (
<li …). That element references the
page-item CSS class. In the code for this article, this class is defined in the Bootstrap CSS framework. However, if it weren’t defined there, it would be your responsibility to ensure that it was defined somewhere. The second CSS class is the one that’s most relevant to this article, though.
active CSS class is used to identify the currently selected page. For this article, this CSS class is also defined in the Bootstrap CSS. As shown in the snippet above, the
Continue reading %Conditionally Applying a CSS Class in Vue.js%