菜单
×
   ❮   
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 提供支持