官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 婺源县| 安庆市| 定州市| 冀州市| 沈阳市| 英吉沙县| 北碚区| 南皮县| 凤山县| 长治市| 惠安县| 和政县| 新建县| 慈利县| 柯坪县| 杭锦后旗| 临清市| 贵定县| 石河子市| 庆安县| 台山市| 渭南市| 富川| 土默特左旗| 维西| 寿光市| 古丈县| 桂东县| 抚松县| 灌南县| 高碑店市| 泾源县| 孟村| 景泰县| 深水埗区| 镇宁| 钟祥市| 永定县| 鄂托克旗| 武定县| 葵青区|