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

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:

主站蜘蛛池模板: 陈巴尔虎旗| 蓝田县| 乌恰县| 怀宁县| 会东县| 霍邱县| 油尖旺区| 九寨沟县| 石柱| 德庆县| 新民市| 甘泉县| 鹰潭市| 平江县| 满洲里市| 兴仁县| 尚志市| 松潘县| 陵水| 汤原县| 特克斯县| 梅州市| 夹江县| 屏东市| 宁国市| 绍兴市| 郯城县| 邛崃市| 苍南县| 武陟县| 宝兴县| 岳池县| 武汉市| 华宁县| 梓潼县| 广饶县| 兴山县| 呼伦贝尔市| 五大连池市| 高碑店市| 鲜城|