Original Source: https://www.sitepoint.com/conditionally-applying-css-class-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. Luckily, Vue provides a way to conditionally apply a CSS class to an element, which I’m going to demonstrate 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:
<nav aria-label=”Page navigation example”>
<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>
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.
The post How to Conditionally Apply a CSS Class in Vue.js appeared first on SitePoint.