5、Vue 3 (2024 版)基础笔记 - if 条件渲染
准备工作
1、创建一个组件
src/components/IfDemo.vue
<template></template>
<script setup lang="ts"></script>
2、引入组件
src/App.vue
<template>
...
<if-demo></if-demo>
</template>
<script setup lang="ts">
import IfDemo from "@/components/IfDemo.vue";
...
</script>
v-if
v-if
指令用于条件性地渲染一块内容。这块内容只会在指令的表达式返回真值时才被渲染。
src/components/IfDemo.vue
<template>
<div v-if="flag">你来找我呀</div>
</template>
<script setup lang="ts">
// 由于 flag 为 false,因此看不见内容
const flag = false
</script>
v-else
条件分支,当一个不满足条件时,去执行另外一个。
<template>
<div v-if="flag">你来找我呀</div>
<!-- 此行内容被渲染 -->
<div v-else>我找不着你,你在哪呢</div>
</template>
<script setup lang="ts">
const flag = false
</script>
v-else-if
src/components/IfDemo.vue
<template>
<div v-if="gender === 1">男人</div>
<div v-else-if="gender === 2">女人</div>
<div v-else>人妖</div>
</template>
<script setup lang="ts">
const gender = 3
</script>
v-show
src/components/IfDemo.vue
<template>
<div v-show="gender == 1">你是男人,所以你出现了</div>
</template>
<script setup lang="ts">
const gender = 1
</script>
template 上的 v-if
src/components/IfDemo.vue
<template>
<template v-if="flag">
<p>我今年 18</p>
<p>我是个美女</p>
</template>
<p>我是王美丽呀</p>
</template>
<script setup lang="ts">
// 为 false 时,template 内的元素都不显示
const flag = false
</script>
请登录后再评论