Vue.js v-if / v-else

示例

假设我们有一个Vue.js实例定义为:

var vm = new Vue({
    el: '#example',
    data: {
        a: true,
        b: false
    }
});

您可以通过包含v-if指令有条件地呈现任何html元素;包含v-if的元素仅在条件评估为true时才会呈现:

<!-- will render 'The condition is true' into the DOM -->
<div id="example">
    <h1 v-if="a">The condition is true</h1>
</div>

<h1>在这种情况下,该元素将呈现,因为变量'a'为true。v-if可以与任何计算结果为布尔值的表达式,计算属性或函数一起使用:

<div v-if="0 === 1">                  false; won't render</div>
<div v-if="typeof(5) === 'number'">   true; will render</div>

您可以使用一个template元素将多个元素归为一个条件:

<!-- in this case, nothing will be rendered except for the containing 'div' -->
<div id="example">
    <template v-if="b">
        <h1>Heading</h1>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
    </template>
</div>

使用时v-if,还可以选择将反条件与v-else指令集成在一起。仅当先前v-if的条件为false时,才显示元素内包含的内容。请注意,这意味着带有v-else的元素必须立即出现在带有v-if的元素之后。

<!-- will render only 'ELSE' -->
<div id="example">
    <h1 v-if="b">IF</h1>
    <h1 v-else="a">ELSE</h1>
</div>

就像v-if一样,使用v-else也可以将多个html元素组合在一起<template>:

<div v-if="'a' === 'b'"> This will never be rendered. </div>
<template v-else>
    <ul>
      <li> You can also use templates with v-else. </li>
      <li> All of the content within the template </li>
      <li> will be rendered. </li>
    </ul>
</template>