# Conditional / v-if

# Conditional v-if/v-else

Using "v-if, v-else-if, v-else", the false ones will be "rendered out" of the DOM entirely.

# Input:











 
 
 
 







 





<template>
  <div>
    <input
      @click="showing = !showing"
      class="switch"
      type="checkbox"
      id="switch"
      name="some-switch"
    />
    <label class="toggle" for="switch"></label>
    <!-- The "false" values are NOT rendered in the DOM -->
    <p v-if="showing">"First Option"<span> /and its childs</span></p>
    <p v-else-if="!showing">"Second option"</p>
    <p v-else>Can't see me</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      showing: true
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# Output:

"First Option" /and its childs

# Conditional using a template

Use v-if on a template, it won't be rendered as a div that isn't necessarily needed.

# Input:











 
 
 
 
 







 





<template>
  <div>
    <input
      @click="showing = !showing"
      class="switch-template"
      type="checkbox"
      id="switch-template"
      name="some-switch-template"
    />
    <label class="toggle" for="switch-template"></label>
    <!-- Use v-if on template, not to add useless div  -->
    <template v-if="showing">
      <h3>Title</h3>
      <h6>SubTitle</h6>
    </template>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      showing: true
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# Output:

Title

SubTitle

# Conditional using v-show

Use V-Show to keep data in the DOM with a "display:none"

# Input:











 
 







 





<template>
  <div>
    <input
      @click="showing = !showing"
      class="switchShow"
      type="checkbox"
      id="switchShow"
      name="some-switchShow"
    />
    <label class="toggle" for="switchShow"></label>
    <!-- The "false" values are rendered and display:none in the DOM-->
    <p v-show="showing">"See you in the DOM!</span></p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      showing: true,
    };
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

TIP

Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs. So prefer v-show if you need to toggle something very often, and prefer v-if if the condition is unlikely to change at runtime.

# Output:

"See you in the DOM!

# Conditional with JS in template

# Input:





 













<template>
  <div>
    <label>Number of states in the USA</label>
    <input type="number" v-model="states" />
    <p>{{ states == 50 ? 'Yes' : 'No' }}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      states: '49'
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# Output:

No

# See the official Vue.js doc