vuejs
/

Vue v-if Directive

Last Sync: Today

On this page

9
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

vuejs

Vue v-if Directive

What is v-if?

The v-if directive is used to conditionally render elements in the DOM based on a boolean expression.

Basic Syntax

HTMLRead-only
1
<p v-if="isVisible">Hello Vue</p>

v-else and v-else-if

HTMLRead-only
1
<p v-if="score > 80">Excellent</p>
<p v-else-if="score > 50">Good</p>
<p v-else>Try Again</p>

Toggle Example

HTMLRead-only
1
<button @click="show = !show">Toggle</button>
<p v-if="show">Visible Content</p>

v-if vs v-show

Featurev-ifv-show
RenderingAdds/removes from DOMUses CSS display
PerformanceSlower for frequent togglesFaster toggling
Initial LoadLazyAlways rendered

When to Use v-if

  • When condition changes rarely
  • When elements should not exist in DOM initially
  • For conditional component rendering

Best Practices

  • Use v-if for heavy components
  • Use v-show for frequent toggling
  • Keep conditions simple
  • Avoid complex logic inside templates

Common Mistakes

  • Using v-if for frequent toggling
  • Complex conditions inside template
  • Forgetting v-else pairing rules
  • Mixing v-if with v-for improperly

Conclusion

The v-if directive is essential for conditional rendering in Vue. It allows dynamic control over the DOM and improves application flexibility.

Try it yourself

<button @click="show = !show">Toggle</button>
<p v-if="show">Hello Vue</p>

Test Your Knowledge

Q1
of 3

v-if does?

A
Hide element
B
Remove/add DOM
C
Style element
D
Bind data
Q2
of 3

Which is faster for toggle?

A
v-if
B
v-show
C
v-bind
D
v-for
Q3
of 3

Which is conditional directive?

A
v-for
B
v-if
C
v-bind
D
v-model

Frequently Asked Questions

What is v-if?

It conditionally renders elements based on a condition.

Difference between v-if and v-show?

v-if adds/removes elements, v-show toggles visibility using CSS.

When to use v-if?

When conditions change rarely.

Previous

vue interpolation

Next

vue v for

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.