【vue】v-for和v-if一起使用的报错

1,665 阅读1分钟

错误说明

v-for和v-if写在同一个标签上会报错

<el-checkbox 
    v-for="it in item.options" 
    :label="it.value" 
    :key="it.value" 
    v-if="it.value !== '其他'">
    {{ it.label }}
 </el-checkbox>

提示:The 'undefined' variable inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'

  • 原因:v-for的优先级会高于v-if,因此v-if会重复运行在每个v-for中。

解决

使用template标签进行包裹(template为html5的新标签,无特殊含义)

<template v-for="it in item.options">
   <el-checkbox 
       :label="it.value" 
       :key="it.value" 
       v-if="it.value !== '其他'">
       {{ it.label }}
   </el-checkbox>
</template>