- 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:

- Vue 3移動(dòng)Web開發(fā)與性能調(diào)優(yōu)實(shí)戰(zhàn)
- Qt 5 and OpenCV 4 Computer Vision Projects
- Modular Programming with Python
- Java FX應(yīng)用開發(fā)教程
- TestNG Beginner's Guide
- Django Design Patterns and Best Practices
- WordPress Plugin Development Cookbook(Second Edition)
- ADI DSP應(yīng)用技術(shù)集錦
- 用戶體驗(yàn)增長(zhǎng):數(shù)字化·智能化·綠色化
- Building Microservices with .NET Core
- 好好學(xué)Java:從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- Principles of Strategic Data Science
- INSTANT Apache Hive Essentials How-to
- Java RESTful Web Service實(shí)戰(zhàn)
- SAS編程演義