美文网首页
v-if 和 v-for 同阶使用

v-if 和 v-for 同阶使用

作者: 缘之空_bb11 | 来源:发表于2025-03-04 16:12 被阅读0次

当它们同时存在于一个节点上时,v-if 比 v-for 的优先级更高。这意味着 v-if 的条件将无法访问到 v-for 作用域内定义的变量别名:

<!--
 这会抛出一个错误,因为属性 todo 此时
 没有在该实例上定义
-->
<li v-for="todo in todos" v-if="!todo.isComplete">
  {{ todo.name }}
</li>

在外先包装一层 <template> 再在其上使用 v-for 可以解决这个问题 (这也更加明显易读)

<template v-for="todo in todos">
  <li v-if="!todo.isComplete">
    {{ todo.name }}
  </li>
</template>

总结: 不要同阶使用, 同阶使用时会优先执行v-if.

相关文章

网友评论

      本文标题:v-if 和 v-for 同阶使用

      本文链接:https://www.haomeiwen.com/subject/tlbhmjtx.html