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

Conditional templates with v-if

We need one last thing before testing our change; the main and preview panes shouldn't be displayed if no note is selected--it would not make sense for the user to have an empty editor and preview pane pointing to nothing, and it would make our code crash since selectedNote would be null. Thankfully, the v-if directive can dynamically take parts out of the template when we want. It works just like the JavaScript if keyword, with a condition.

In this example, the p element will not be in the DOM at all while the loading property is falsy:

<p v-if="loading">
  Loading...
</p>

There are also two other useful directives, v-else and v-else-if, that will work as you might have expected:

<p v-if="loading">
  Loading...
</p>

<p v-else-if="processing">
  Processing
</p>

<p v-else>
  Content here
</p>

Back in our app, add the v-if="selectedNote" condition to both the main and preview panes so that they are not added to the DOM until a note is selected:

<!-- Main pane -->
<section class="main" v-if="selectedNote">
  ...
</section>

<!-- Preview pane -->
<aside class="preview" v-if="selectedNote" v-html="notePreview">
</aside>

The repetition here is a bit unfortunate, but Vue has us covered. You can surround both elements with a special <template> tag that acts like braces in JavaScript:

<template v-if="selectedNote">
  <!-- Main pane -->
  <section class="main">
    ...
  </section>

  <!-- Preview pane -->
  <aside class="preview" v-html="notePreview">
  </aside>
</template>

At this point, the app should look like this:

The <template> tag will not be present in the DOM; it is more like a ghost element that is useful to regroup real elements together.

主站蜘蛛池模板: 光山县| 西昌市| 临夏市| 肇源县| 鹤庆县| 阿勒泰市| 甘德县| 富蕴县| 阿图什市| 图们市| 凤山市| 鄂托克旗| 柳州市| 贵州省| 科尔| 商都县| 河南省| 崇州市| 临夏市| 越西县| 金乡县| 兰溪市| 昌邑市| 西乌珠穆沁旗| 西城区| 东光县| 尼勒克县| 彭山县| 武定县| 获嘉县| 尉犁县| 揭西县| 上犹县| 广宗县| 德昌县| 阜新| 延长县| 涡阳县| 沙河市| 社旗县| 荃湾区|