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

- 大學(xué)計(jì)算機(jī)應(yīng)用基礎(chǔ)實(shí)踐教程
- PHP網(wǎng)絡(luò)編程學(xué)習(xí)筆記
- Hands-On JavaScript High Performance
- Koa開發(fā):入門、進(jìn)階與實(shí)戰(zhàn)
- MATLAB實(shí)用教程
- Java Web應(yīng)用開發(fā)技術(shù)與案例教程(第2版)
- 可解釋機(jī)器學(xué)習(xí):模型、方法與實(shí)踐
- Node Cookbook(Second Edition)
- 微信小程序開發(fā)與實(shí)戰(zhàn)(微課版)
- Python+Tableau數(shù)據(jù)可視化之美
- 匯編語言編程基礎(chǔ):基于LoongArch
- 快速入門與進(jìn)階:Creo 4·0全實(shí)例精講
- 一步一步跟我學(xué)Scratch3.0案例
- C語言程序設(shè)計(jì)
- 高效使用Greenplum:入門、進(jìn)階與數(shù)據(jù)中臺(tái)