1. v-if v-else-if v-else
和js代码一样,if可以嵌套,并且elseif else都必须有对应的if(猜测也是就近匹配)
<template>
<div v-if="type === 'A'">
A
</div>
<div v-else-if="type === 'B'">
B
</div>
<div v-else-if="type === 'C'">
C
</div>
<div v-else>
Not A/B/C
</div>
</template>
<template>可以作为容器包裹元素,最终不渲染
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
2. v-show
v-show用法基本和v-if一样,不同的是
- v-show为flase的元素并不是不渲染,而是将元素style="display: none;"
- v-show不支持<template>
- v-show不支持v-else
使用:如果需要非常频繁地切换,则使用 v-show
较好;如果在运行时条件很少改变,则使用 v-if
较好
3. v-if和v-for一起使用
永远不要在一个元素上同时使用 v-if
和 v-for
如果同时使用会报错:This 'v-if' should be moved to the wrapper element
需要将它们中的一个放到template
<template v-if="true">
<div v-for="(user, index) in users" :key="index">{{user}}</div>
</template>
<template v-for="(user, index) in users" :key="index">
<div v-if="user">{{user}}</div>
</template>