v-if 和 v-for
优先级
可以稍微试一下, 会发现一起用会报错.
vue
<script lang="ts" setup>
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }];
</script>
<template>
<div
class="h-full w-full"
@my-test-event="handler"
>
<div
v-for="item in arr"
v-if="item.id === 1"
>
{{ item.id }}
</div>
</div>
</template>
会报错Cannot read properties of undefined (reading 'id')
, 这是因为v-if的优先级更高, 实际的执行顺序应该是先判断v-if, 再去执行v-for. 因此, 判断v-if时item是undefined.
v-show的优先级没v-for高, 因此没有报错, 并且正确地显示了1, 其他的没有显示.
不过即使这样, 可读性也不高, 应该再套一层.
vue
<script lang="ts" setup>
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }];
</script>
<template>
<div
class="h-full w-full"
@my-test-event="handler"
>
<div
v-for="item in arr"
:key="item.id"
>
<!-- 或者v-show -->
<template v-if="item.id === 1">
{{ item.id }}
</template>
</div>
</div>
</template>
但是更好的办法是使用computed来过滤数组.