選單
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP 如何 W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue 教程

Vue 首頁 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue 為何、如何及設定 Vue 第一個 SFC 頁面 Vue 元件 Vue Props Vue v-for 元件 Vue $emit() Vue 穿透屬性 Vue 作用域樣式 Vue 區域性元件 Vue 插槽 Vue v-slot Vue 作用域插槽 Vue 動態元件 Vue Teleport Vue HTTP 請求 Vue 模板引用 Vue 生命週期鉤子 Vue Provide/Inject Vue 路由 Vue 表單輸入 Vue 動畫 Vue v-for 動畫 Vue 構建 Vue 組合式 API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

Vue v-if 指令


示例

使用 v-if 指令建立一個 <div> 元素,如果條件為 'true'。

<div v-if="createImgDiv">
  <img src="/img_apple.svg" alt="apple">
  <p>This is an apple.</p>
</div>
執行示例 »

更多示例請參見下方。


定義和用法

v-if 指令用於條件性地渲染一個元素。

v-if 用於一個元素時,它必須後跟一個表示式。

  • 如果表示式的值為 'true',則該元素及其所有內容將在 DOM 中建立。
  • 如果表示式的值為 'false',則該元素將被銷燬。

當一個元素使用 v-if 進行切換時

  • 我們可以使用內建的 <Transition> 元件來為元素進入和離開 DOM 時新增動畫。
  • 生命週期鉤子(如 'mounted' 和 'unmounted')會被觸發。

注意:不建議在同一個標籤上同時使用 v-ifv-for。如果這兩個指令在同一個標籤上使用,v-if 將無法訪問 v-for 使用的變數,因為 v-if 的優先順序高於 v-for


條件渲染指令

本概述描述了用於條件渲染的不同 Vue 指令是如何協同工作的。

指令 詳情
v-if v-if 可以單獨使用,也可以與 v-else-if 和/或 v-else 結合使用。如果 v-if 中的條件為“true”,則不考慮 v-else-ifv-else
v-else-if 必須在 v-if 或另一個 v-else-if 之後使用。如果 v-else-if 中的條件為“true”,則不考慮後續的 v-else-ifv-else
v-else 如果 if 語句的第一個部分為 false,則會執行此部分。必須放在 if 語句的最後,在 v-ifv-else-if 之後。

更多示例

示例 1

使用 v-if 將資料屬性作為條件表示式,並結合 v-else

<p v-if="typewritersInStock">
  有庫存
</p>

<p v-else>
  無庫存
</p>
自己動手試一試 »

示例 2

使用 v-if 將比較檢查作為條件表示式,並結合 v-else

<p v-if="typewriterCount > 0">
  有庫存
</p>

<p v-else>
  無庫存
</p>
自己動手試一試 »

示例 3

結合使用 v-ifv-else-ifv-else,根據庫存的打字機數量顯示狀態訊息。

<p v-if="typewriterCount>3">
  有貨
</p>

<p v-else-if="typewriterCount>0">
  所剩不多!
</p>

<p v-else>
  缺貨
</p>
自己動手試一試 »

示例 4

使用 v-if 將原生 JavaScript 方法作為條件表示式,並結合 v-else

<div id="app">
  <p v-if="text.includes('pizza')">文字包含單詞 'pizza'</p>
  <p v-else>文字中未找到“pizza”一詞</p>
</div>
data() {
  return {
    文字: '我喜歡墨西哥捲餅、披薩、泰式牛肉沙拉、河粉和塔吉鍋。'
  }
}
自己動手試一試 »

示例 5

當從 API 接收到資料時,使用 v-if 渲染 <div> 標籤。

<template>
  <h1>Example</h1>
  <p>Click the button to fetch data with an HTTP request.</p>
  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>
  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>
  <button @click="fetchData">Fetch data</button>
  <div v-if="data" id="dataDiv">
    <img :src="data.avatar" alt="avatar">
    <pre>{{ data.first_name + " " + data.last_name }}</pre>
    <p>"{{ data.employment.title }}"</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        data: null,
      };
    },
    methods: {
      async fetchData() {      
        const response = await fetch("https://random-data-api.com/api/v2/users"); 
        this.data = await response.json();
      },    
    }
  };
</script>

<style>
#dataDiv {
  width: 240px;
  background-color: aquamarine;
  border: solid black 1px;
  margin-top: 10px;
  padding: 10px;
}
#dataDiv > img {
  width: 100%;
}
pre {
  font-size: larger;
  font-weight: bold;
}
</style>
執行示例 »

示例 6

使用 v-if 建立元件,以便觸發 mounted 生命週期鉤子。

CompOne.vue:

<template>
    <h2>Component</h2>
    <p>Right after this component is added to the DOM, the mounted() function is called and we can add code to that mounted() function. In this example, an alert popup box appears after this component is mounted.</p>
    <p><strong>Note:</strong> The reason that the alert is visible before the component is visible is because the alert is called before the browser gets to render the component to the screen.</p>
  </template>
  
  <script>
  export default {
    mounted() {
      alert("The component is mounted!");
    }
  }
  </script>

App.vue:

<template>
  <h1>The 'mounted' Lifecycle Hook</h1>
  <button @click="this.activeComp = !this.activeComp">Create component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin: 10px;
    width: 400px;
    background-color: lightgreen;
  }
</style>
執行示例 »

示例 7

使用 v-if 切換 <p> 元素,以便觸發動畫。

<template>
  <h1>Add/Remove <p> Tag</h1>
  <button @click="this.exists = !this.exists">{{btnText}}</button><br>
  <Transition>
    <p v-if="exists">Hello World!</p>
  </Transition>
</template>

<script>
export default {
  data() {
    return {
      exists: false
    }
  },
  computed: {
    btnText() {
      if(this.exists) {
        return 'Remove';
      }
      else {
        return 'Add';
      }
    }
  }
}
</script>

<style scoped>
  .v-enter-from {
    opacity: 0;
    translate: -100px 0;
  }
  .v-enter-to {
    opacity: 1;
    translate: 0 0;
  }
  .v-leave-from {
    opacity: 1;
    translate: 0 0;
  }
  .v-leave-to {
    opacity: 0;
    translate: 100px 0;
  }
  p {
    background-color: lightgreen;
    display: inline-block;
    padding: 10px;
    transition: all 0.5s;
  }
</style>
執行示例 »

相關頁面

Vue 教程:Vue v-if 指令

Vue 參考:Vue v-else-if 指令

Vue 參考:Vue v-else 指令

Vue 教程: Vue 動畫

Vue 教程:Vue 生命週期鉤子


×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援