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

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:

主站蜘蛛池模板: 哈巴河县| 定州市| 仪陇县| 镶黄旗| 阜新市| 铁力市| 常熟市| 许昌市| 平定县| 蓬安县| 积石山| 临漳县| 奇台县| 阿勒泰市| 阜阳市| 伊金霍洛旗| 新营市| 河源市| 教育| 三门县| 汝城县| 韩城市| 苏尼特左旗| 开江县| 天津市| 临城县| 调兵山市| 铜梁县| 布尔津县| 汾阳市| 漠河县| 田林县| 改则县| 江城| 阿城市| 乌兰察布市| 葫芦岛市| 正定县| 綦江县| 蕲春县| 双桥区|