vue登峰造极的Vue

v-for和v-if一起使用时的坑

2019-08-09  本文已影响0人  Tme_2439
缘由:

在进行项目开发的时候因为在一个标签上同时使用了v-for和v-if两个指令导致的报错。

报错代码如下:
<el-input 
      type="textarea"
     :autosize="{ minRows: 2, maxRows: 8}"
     v-for="Oitem in Object.keys(cItem)"
     :key="Oitem"
     v-if="Oitem !== 'title'"
     v-model="cItem[Oitem]">
</el-input>

提示错误: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="Oitem in Object.keys(cItem)">
          <el-input 
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 8}"
              :key="Oitem"
              v-if="Oitem !== 'title'"
              v-model="cItem[Oitem]">
           </el-input>
</template>

注意点:key值写在包裹的元素中

上一篇 下一篇

猜你喜欢

热点阅读