← Back to Vue.js Course | Chapter 2: Template Syntax | Lesson 3 of 7

v-if/v-else का उपयोग

v-if एक element को page में तभी add करता है जब इसकी condition true हो, alternatives के लिए v-else-if और v-else के साथ।

In this page:

  1. v-if/v-else
Syntax
markup
<p v-if="condition">shown when true</p>
<p v-else-if="other_condition">other</p>
<p v-else>otherwise</p>

v-if/v-else

v-if एक condition के आधार पर element को DOM में render या remove करता है। v-else-if और v-else को सीधे इसके बाद आना चाहिए। एक साथ कई elements toggle करने के लिए, एक template tag पर v-if डालें।

Elements remove और create करने की एक cost है, इसलिए frequent toggling के लिए v-show इस्तेमाल करें।

Note: v-else को एक v-if या v-else-if element के तुरंत बाद आना चाहिए।

उदाहरण: v-if/v-else

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <p v-if="score >= 90">Grade A</p>
  <p v-else-if="score >= 75">Grade B</p>
  <p v-else>Keep practising</p>
  <template v-if="loggedIn">
    <h3>Welcome back</h3>
    <p>You have new mail.</p>
  </template>
</div>
<script>
  Vue.createApp({
    data() { return { score: 82, loggedIn: true }; },
  }).mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Grade BWelcome backYou have new mail.
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. v-if और v-else के बीच दूसरे elements रखना
  2. एक element पर v-if और v-for साथ इस्तेमाल करना
  3. rapid toggles के लिए v-if इस्तेमाल करना
चैप्टर सारांश
  • v-if elements add या remove करता है
  • v-else-if और v-else इसे follow करते हैं
  • template v-if elements group करता है
  • Frequent toggles के लिए v-show prefer करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.