Many times the CSS class name of an element needs to be changed when the Web is running. But when changing class names, sometimes it's best to conditionally apply the style. For example, you have a page turning effect. The page turning effect usually has a highlighting effect, which is used to display the current page to the user, which is very helpful to the user. The item's style is conditionally set, based on the page currently being viewed.
This article mainly introduces the conditional use of CSS classes in Vue. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
A common effect of page turning looks like this:
In this example, there are five pages, and only one of them is selected at a time. If you build a paginator with Bootstrap, the selected page will have a CSS class named active applied to the list items. If the page is the currently viewed page, then you want this class to be applied. In other words, you want to apply the active classname conditionally. In Vue, a method is provided to conditionally apply CSS classes to elements. This technology will be demonstrated to you in the following content.
To conditionally apply a CSS class at runtime, it needs to be bound to a JavaScript object. To complete this task successfully, two steps must be completed. First, you must ensure that the CSS class name is defined, and then create the class binding in the template. I'll explain these steps in detail elsewhere in this article.
Step1: Define your CSS class names
Imagine that, over a period of time, the five pages shown in the image above were recommended using HTML code like the following Constructed:
<p id="myApp"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >1</a></li> <li class="page-item"><a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >2</a></li> <li class="page-item active"><a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >3</a></li> <li class="page-item"><a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >4</a></li> <li class="page-item"><a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >5</a></li> </ul> </nav> </p>
Note: Each list item li in this code snippet represents each page. The changed element references the page-item class name. In this code, the Bootstrap CSS framework is used. However, if it is not defined, then make sure it is defined somewhere. However, the second CSS class is the most relevant to this article. The CSS class name of
active is used to identify the currently selected page. In this article, this CSS class is also commonly used in the Bootstrap framework. As shown in the code snippet above, the active class is only used in the third list item element. As you might guess, this is the CSS class you want to apply conditionally. To do this, you need to add a JavaScript object.
Step2: Bind your CSS class name
Let’s restructure the code in step one. When creating class bindings in templates, you have two main options: use object syntax or use array syntax. Next, I'll show you how to use both methods.
Using Object Syntax
To create a class binding using object syntax, you must use JavaScript expressions. The expressions we will use can be seen in the code below. The relevant code is as follows:
<p id="myApp"> <nav aria-label="An example with pagination"> <ul class="pagination"> <li v-for="page in totalPages" v-bind:class="{'page-item':true, 'active':(page === currentPage)}"> <a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ page }}</a> </li> </ul> </nav> </p>
In order to reduce the amount of code, the v-for directive in Vue is used here. This directive is used to render items in a loop. The item in this example is the page itself. In addition to using the v-for directive, the v-bind directive is also used.
The v-bind directive binds the element's class attribute to an instance of Vue. The Vue instance is defined like this:
var app = new Vue({ el: '#myApp', data: { totalPages: 5, currentPage: 3 } });
The data object on this Vue instance includes a property named currentPage. If you revisit the HTML template defined above, you will notice that this attribute is being referenced. In fact, the JavaScript object associated with each class binding looks like this:
{'page-item':true, 'active':(page === currentPage)}
This object defines two properties: page-item and active . It's worth noting that these are the names of the two CSS classes discussed in step one. In step 2, these two class references have become property names in the JavaScript object. The values associated with these property names are JavaScript expressions. If the expression evaluates to true , the CSS class name will be included. If the expression evaluates to false , the CSS class is not included. With these rules in place, let's look at each property.
The first attribute page-item has a true value. This hardcoded value is used because we always want to include the page-item class. The second property is active , which uses a JavaScript expression. When this expression is true, the active class is applied. This uses us to conditionally apply the active class based on the value of currentPage.
body { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; } .pagination { justify-content: center; }
Every time the value of currentPage is modified, active will be applied to its corresponding list item. For example, the effect below:
#Another way to conditionally apply the active class is to bind it to an array.
Using array syntax
Vue allows adding CSS class names to lists by binding to an array. If you want to use array syntax, the HTML structure in step 1 needs to be adjusted. The modified code is as follows:
<p id="myApp"> <nav aria-label="An example with pagination"> <ul class="pagination"> <li v-for="page in totalPages" v-bind:class="[pageItemClass, (page === currentPage) ? activeClass : '']"> <a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ page }}</a> </li> </ul> </nav> </p>
和上一个示例的区别就是类绑定上使用数组。这种替代方法需要在 data 对象中添加两个额外的属性。这两个属笥是 pageItemClass 和 activeClass 。更新Vue初始化的代码:
var app = new Vue({ el: '#myApp', data: { totalPages: 5, currentPage: 3, pageItemClass: 'page-item', activeClass: 'active' } });
正如你看到了, data 对象变了,虽然 data 对象大小变大了,但是使用数组语法时,模板中的代码稍微干净一些。对象语法更紧凑一些。
对象语法和数组语法之间的选择归结为个人爱好。
这两种方法都可能使你的HTML模板更加复杂。然而,实际上还有更多的事情发生。在实现中,我们正在关注如何分离。我们正在创建一个由数据驱动的模板。这使用的视图更容易测试,并且在应用程序变大时更容易维护。
总结
本文根据 @Chad Campbell 的《 Conditionally Applying a CSS Class in Vue.js 》所译,整个译文带有我们自己的理解与思想,如果译得不好或有不对之处还请同行朋友指点。如需转载此译文,需注明英文出处: https://www.sitepoint.com/conditionally-applying-css-class-vue-js/ 。
相关推荐:
The above is the detailed content of Detailed explanation of conditionally using CSS class instances in Vue. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
