- Vue.js 2 Web Development Projects
- Guillaume Chau
- 212字
- 2021-07-02 22:34:28
Dynamic CSS classes
It would be nice to add a selected CSS class when a note is the selected one in the note list (for example, to display a different background color). Thankfully, Vue has a very useful trick to help us achieve this--the v-bind directive (the : character being its shorthand) has some magic to make the manipulation of CSS classes easier. Instead of passing a string, you can pass an array of strings:
<p :class="['one', 'two', 'three']">
We will get the following in the DOM:
<p class="one two three">
However, the most interesting feature is that you can pass an object whose keys are the class names and whose values are Booleans that determine whether or not each class should be applied. Here is an example:
<p :class="{ one: true, two: false, three: true }">
This object notation will produce the following HTML:
<p class="one three">
In our case, we want to apply the selected class only if the note is the selected one. So, we will simply write as follows:
<p :class="{ selected: note === selectedNote }">
The note list should now look like this:
<p class="notes"> <p class="note" v-for="note of notes" @click="selectNote(note)"
:class="{selected: note === selectedNote}">{{note.title}}</p> </p>
You can combine a static class attribute with a dynamic one. It is recommended that you put the nondynamic classes into the static attribute because Vue will optimize the static values.
Now, when you click on a note in the list to select it, its background will change color:

- Beginning Java Data Structures and Algorithms
- Mastering Ember.js
- 算法訓(xùn)練營:入門篇(全彩版)
- Mastering Ubuntu Server
- The Computer Vision Workshop
- Nginx實戰(zhàn):基于Lua語言的配置、開發(fā)與架構(gòu)詳解
- Lighttpd源碼分析
- Java網(wǎng)絡(luò)編程實戰(zhàn)
- MyBatis 3源碼深度解析
- Spring Boot學(xué)習(xí)指南:構(gòu)建云原生Java和Kotlin應(yīng)用程序
- Instant SQL Server Analysis Services 2012 Cube Security
- 編程真好玩:從零開始學(xué)網(wǎng)頁設(shè)計及3D編程
- Hadoop實戰(zhàn)
- Procedural Content Generation for Unity Game Development
- Python游戲趣味編程